Edx html5 0 - Intro
Edx html5 0 - Intro
Course
Alan Updates and News
July 19, 2016
What
Welcome to the HTML5 Introduction course!
news have
you
Hello, brought
about the
Thank sheep-
you for registering to this HTML5 Introduction course, where you will
learn the basic building blocks of Web design and style – HTML5 and CSS – to
stealer,
give your site a professional look and feel.
uncle?
To get started, please read the "Course practical information" section, where
you can become oriented to the course structure, the schedule, and how things
will work in this course.
Additionnal information:
If you are new to the edX platform, we encourage you to check out DemoX, a
quick walk-through of an edX experience. It will help answer basic “how to's”
on taking an edX course. For more detailed info, please check the edX
Learner’s Guide (September 2016) (long pdf file!).
To get help with a technical problem with the edx platform, click "Help" (on the
left side of this page) to send a message to the edX student support.
Join our Facebook page, and follow us on Twitter (@thew3cx).
Course outline
Week 6 is about page layout and more specifically about the flexbox module.
Using flexible widths and heights, elements can be aligned to fill a space or
distribute space between elements, which makes it a great tool to use for
responsive design systems. Once you've got the basics, practice more with this
fun Flexbox Froggy game. Note that some parts of this week are clearly
indicated OPTIONAL, meaning that there will be no questions related to that
content material.
Verified Certificate
W3C provides a W3Cx Verified Certificate for this course that lets you
demonstrate to employers, colleagues, and professional organizations that you
successfully completed a course that increased your mastery of HTML5. This
certificate can be used to highlight newly acquired skills on your resume or
LinkedIn profile.
Once you have a passing score (70% or higher), you can
click the "Request Certificate" button on the course
progress page. The certificate will then be generated
and ready within a minute - read more detailed info.
Note that this course does not offer Honor of Code
certificates. Please write to [email protected] if you
encounter an issue with the paiement of your certificate.
You can share your purchased Web certificate on Facebook, LinkedIn, and
Twitter (find more info. in this page)
This HTML5 Introduction course is part of the HTML5 from W3C XSeries. To get
an XSeries certificate, you will need to successfully pass the 3 HTML5 courses
and as such also enroll to the HTML5 Part 1 course and the HTML5 Part 2
course.
We sincerely hope that you will enjoy this W3Cx course, designed in
collaboration with Intel.
Course Evaluation
Feedback please!
What is W3C?
In April 1995, Inria became the first European W3C host, followed by Keio
University of Japan (Shonan Fujisawa Campus) in Asia in 1996. In
2003, ERCIM took over the role of European W3C Host from Inria. In 2013, W3C
announced Beihang University as the fourth Host.
In addition to these four Host locations that employ W3C staff, there are W3C
Offices around the globe that support the developer communities in their
regions and organize local events. Find the one next to your place!
A few figures
As of March 2016, W3C is:
A member-driven organization composed of over 400
companies, universities, start-ups, etc. from all over the
world.
56 technicals groups, including Working, and Interest
Groups where technical specifications are discussed and
developed.
Over 4954 published technical reports, including 357 Web
standards (or W3C Recommendations) - since January
1st ,1995.
About 244 Community and Business Groups, where
developers, designers, and anyone passionate about the
Web have a place to hold discussions and publish ideas.
Near 8747 active participants constituting the W3C
community.
A technical staff composed of about 76 people, spread on
all five continents.
What is Web accessibility?
The power of the Web is in its universality.
Access by everyone regardless of disability is an essential
aspect.
Tim Berners-Lee, Director and inventor of the World
Wide Web
Who is impacted?
Web accessibility addresses all disabilities, including hearing, learning and
cognitive, neurological, physical, speech, and visual disabilities. Some
examples of Web accessibility features include:
Captions on audio and multimedia content for people who are hard of hearing;
Clear and consistent layout for people with learning and cognitive disabilities;
Keyboard support for people with physical disabilities and do not use a mouse;
Text alternatives for people with visual disabilities and using screen readers;
There are many simple Web accessibility improvements that you can
implement and check right away, even when you are new to this topic. Two
example excerpts are provided below on this page but you can find more
Good page titles are particularly important for orientation — to help people
know where they are and move between pages open in their browser. The
first thing screen readers say when the user goes to a different Web page is
the page title. In the Web page markup, they are the <title> within the
<head>.
Check #1: There is a title that adequately and briefly describes
Example:
1. <head>
2. ...
3. <title>Web Accessibility Initiative (WAI) - home page</title>
4. ...
5. </head>
(for example, visual, auditory or tactile) to match the needs of the user.
synthesized speech.
text.
Example: See the W3C logo below. It contains a link that points to the
W3C Web site. The text alternative is going to be a brief description of the
link target.
1. <a href="http://w3.org">
2. <img src="www.w3.org/Icons/w3c_home.png" width="72" height="48" al
t="World Wide Web Consortium">
3. </a>
What is internationalization?
Access to the Web for all has been a fundamental concern and goal of the W3C
since the beginning. It is easy to overlook the needs of people from cultures
different to your own, or who use different languages or writing systems, but
you have to ensure that any content or application that you design or develop
is ready to support the international features that they will need.
Unicode
Text in a computer or on the Web is composed of
characters. Charactersrepresent letters of the
alphabet, punctuation, or other symbols.
Example 1:
1. <head>
2. <meta charset="utf-8"/>
3. ...
4. </head>
Check #2: The HTML tag has a lang attribute which correctly indicates
the language of your content.
1. <!doctype html>
2. <html lang="fr">
3. <head>
4. ...
Check #3: If your content will be seen by people from diverse cultures,
check that your cultural references will be recognized and that there
is no inappropriate cultural bias.
Don't worry!
You will learn about the basics as you progress through the course, so don't
worry about things you don't understand on this page – you'll learn about them
shortly. Once you have taken the course, you can find more tips and
information from the W3C at: Internationalization techniques: Authoring HTML
& CSS
When you start creating Web pages, you can also run them through the
W3C's Internationalization Checker. If there are internationalization problems
with your page, this checker explains what they are and what to do about it.
Validators
For almost 15 years, the W3C has been developing and
hosting free and open sourcetools used every day
by millions of Web developers and Web designers.
All the tools listed below are Web-based, and are
available as downloadable sources or as free services on the W3C Developers
tools site.
W3C Validator
The W3C validator checks the markup validity of various Web document
formats, such as HTML.
CSS Validator
The CSS validator checks Cascading Style Sheets (CSS) and (X)HTML
documents that use CSS stylesheets.
Unicorn
Unicorn is W3C's unified validator, which
helps people improve the quality of their
Web pages by performing a variety of
checks. Unicorn gathers the results of the
popular HTML and CSS validators, as well as
other useful services, such as
Internationalization, RSS/Atom feeds and
http headers.
Internationalization Checker
The W3C Internationalization Checker provides information about various
internationalization-related aspects of your page, including the HTTP headers
that affect it. It will also report a number of issues and offer advice about how
to resolve them.
Link Checker
The W3C Link Checker looks for issues in links, anchors and referenced objects
in a Web page, CSS style sheet, or recursively on a whole Web site. For best
results, it is recommended to first ensure that the documents checked use
valid (X)HTML Markup and CSS.
All that is to say that there are lots of options when it comes to creating Web
pages. There are, of course, GUI drag and drop solutions, where you can create
a Web page as you would a diagram or picture, but we want to learn the nitty-
gritty details of HTML, so we'll ignore those options.
An abundance of editors
While any text editor, like NotePad or TextEdit, can be used to create Web
pages, they don't necessarily offer a lot of help towards that end. Other options
offer more facilities for error checking, syntax coloring and saving some typing
by filling things out for you.
One caveat, you need to make sure that whatever editor you choose will save
to a "plain text" format (".txt"). Some editors will save to other formats by
default (.rtf, .doc, etc.) so you need to make sure you save your source code as
plain text.
For our purposes in this course, we'll be showing examples and providing
templates using the Intel XDK. In addition to providing an "HTML aware" editor,
it also provides facilities for viewing your web app and provides easy access to
samples and templates that we'll be using in this course.
Web browsers
First, you can open the file in your browser. Typically if you navigate to an
html file and open it the system will open it with a browser by default. This
should be sufficient for our purposes in this class, but there is one other way to
do it that's worth mentioning.
1.2 The big three: Learn about the basic tools you will use to code for the
Web including hypertext and Web browsers.
1.3 Elements, tags and attributes: Here you will begin learning about the
functions of the different types of code.
1.5 Best practices, the wisdom: Studying other peoples mistakes is a great
way to avoid the same pitfalls.
1.6 More on tags: Review of the tags we have just learned about and get
started on your course project.
1.7 Test your knowledge: Try out these quizzes on all the things that you
have learned in week one.
The Web: vague but exciting!
years ago today, a proposal was sent internally at CERN outlying a universal
linked information system. Dubbed 'Information Management: A proposal',
pictured below, the proposal was created by Sir Tim Berners-Lee and was sent
to his boss Mike Sendall, who described it as 'vague but exciting'.
Sir Tim Berners-Lee’s vision for universality enabled the development of a high-
level network of content that allows any document to link to any other
documents.
The World Wide Web was initially created to make it easier to share research
papers. It is a system of interlinked ‘hypertext’ documents that are accessed
via the Internet; in essence, an information space. While he did not invent
hypertext systems, Berners-Lee proposed using them 'to link and access
information of various kinds as a web of nodes in which the user can browse at
will.'
His breakthrough was to link hypertext to the Internet and he used three
technologies to do this:
In the following pages, we present HTML through what is usually called the big
3 (HTML5, and JavaScript), the hypertext concept and the browser that is an
application program that provides a way to look at and interact with all the
information on the World Wide Web.
CSS
The 'CSS' part (version 3 being current) is
all about the presentation or style of the
page; what it looks like without too much
regard for the specific content. We'll be going into more detail
on that later in this course, but for now, think of it as the way
you might specify a "theme" in a word processing document,
setting fonts, sizes, indentations and whatever else may apply to what it looks
like.
JavaScript
The 'JavaScript' part is about the actions a page can take such as
interaction with the user, and customizing and changing the page
according to any number of parameters. This is what allows a Web page
to be more than just a document, but potentially a Web application, with
nearly unlimited possibilities. We will not be doing much with JavaScript in
this course, but you should know that it is an important leg of the stool for
modern Web pages.
Hypertext
A fundamental key to the World Wide Web is the concept of "Hypertext".
Hypertext is built on the idea of linking information together, not unlike using
footnotes, except much easier and more flexible. The idea was to "Mark Up"
your document with links and define how to break it down into different
segments (chapters, sections, paragraphs, tables, figures, etc.)
The browser
The Internet existed long before the Web
came to fruition, and lots of organizations
were connected to it, including schools,
companies and government organizations. As things progressed through the
80's, the Internet was used for file transfers, newsgroups (a kind of open
forum), email and other conveniences.
There are many ways to markup a document, but HTML borrows a technique
from an ancestor language, SGML (Standard Generalized Markup Language),
which uses angle brackets ("<" and ">") to separate the annotations from the
regular text. In HTML these annotations are called "tags".
1. <body>
2. <h1>A Tale of Two Cities</h1>
3. <p>
4. It was the best of times, it was the worst of times, . . . .
5. </p>
6. ...
7. <p>
8. . . . it is a far, far better rest
9. that I go to than I have ever known.
10. </p>
11. </body>
If you eliminated everything in between the angle brackets from the text, for
most purposes it would still read the same:
Try It Out!
I expect at this point you may be itching to write some HTML code. As is the
tradition in programming tutorials, we'll pause here to create a simple "Hello
World" program. If you went through the preparation for this course, you
should have Intel® XDK installed on your system, or you can choose any other
editor of your liking.
Elements
If you are sitting at a coffee shop next to a table of Web developers, you will
probably hear three words quite a bit: 'Tags', 'Attributes' and 'Elements' (or
sometimes 'DOM elements', same thing just more precise and wordy).
Consider the figure above. It contains a single 'html' element. It turns out this
includes within it the entire content of your html file. If you click on the "html"
node, you'll find that it contains two components, a head and a body. Clicking
on each of those will reveal their respective contents. This structure is what we
computer scientists call a "tree". Any given element (except for the outermost
'html' element) is wholly contained inside another element, referred to as the
"parent" element. Not surprisingly, the elements that a given element contains
are its "child" elements. And, yes, children of a common parent are often
referred to as "siblings".
Thus in the example above, the top element is the html element, which
contains just two elements, the head and body. The head element contains a
title element and the body contains an 'h1' element and a 'p' element. In a
more typical example, the body would contain many more children, but for our
purpose this is enough.
Tags
<html>
<body>
<p>
<em>
that tag (or 'open tag') does, it applies to the content following the tag. Unless
you want that to be the entire rest of the document, you need to indicate when
to stop using that tag and do something else, so '<' and '>' are again used.
Since elements are typically nested within other elements, the browser needs
to be able to distinguish between the end of the current tag or the beginning of
a new tag (representing a nested element). This is done by adding a '/' right
after the '<' to indicated that it's a 'close tag'. To indicate the beginning and
end of a paragraph (indicated by the single letter 'p') you end up with
something like this:
The browser sees the letters '<p>' and decides 'A new paragraph is starting,
I'd better start a new line and maybe it'. Then when it sees '</p>' it knows
that the paragraph it was working on is finished, so it should break the line
there before going on to whatever is next.
For example, the '<em>' tag is used for that needs Emphasis. The '<' and '>'
indicate that this is a tag, and the "little bits of text" in between tell us what
kind of tag it is. To completely describe the element, it needs an open and
close tag, with everything in between the tags is the contents of the element:
Most tags have open and close versions, but there are a few strange ones.
We'll learn more about these later, but we generally refer to the strange ones
as "" tags. these tags represent an element that is completely described by
its attributes, and thus there is no need for other content. So if you see
something like this:
Comments
Computers are great at reading computer languages, but it's not always easy
for humans. Comments are a way of adding some text that is primarily
targeted towards human readers.
An HTML comment tag starts with '<!--' and ends with '-->', meaning that as
the computer is reading through your HTML file, if it sees '<!--' it will ignore
everything it sees until it comes across '-->'. There is no open or close tag, just
a comment tag. Unlike most other things in HTML5, comments cannot be
nested. If you try that, like
1. <!--
2. Beginning of comment
3. <!-- comment nested inside -->
4. This is after the nested comment
5. -->
then the computer will see the beginning of the comment tag and start
ignoring everything until it sees '-->', including the second '<!--'. Once it sees
'-->' it assumes the comment is done and goes back to processing everything it
sees as HTML code and content, even though the writer may have meant it to
be a comment.
Like most other tags, it can span multiple lines of your source file. This can be
really convenient when you have a lot to say:
1. <!--
2. If you want some good advice,
3. Neither a borrower nor a lender be,
4. For loan oft loses both itself and friend,
5. And borrowing dulls the edge of husbandry.
6. -->
Comments are also commonly used in development to block out bits of code,
whether for testing or leaving unfinished business in the file:
It's important to remember that just as HTML, CSS and JavaScript are three
different languages, they each have their own way of writing comments. This
might seem confusing, but it's actually kind of important that the HTML
comments, at least, differ from the others. As for the exact form of those
comments, we'll cover that in good time.
Attributes
Most of what we'll cover about attributes will come later, but I wanted to
introduce the idea briefly. Basically, a given element on your webpage can be
distinguished by any number of unique or common attributes. You can identify
it uniquely with an 'id' attribute, or group it with a class of other elements by
setting the 'class' attribute.
Attributes in HTML are written inside the opening tag like this:
Again, the fact that the computer does not care what we put in those strings
(except for some restrictions) means we can use them to convey meaning to a
human developer. I could just as easily have said id='x' and class='y', but
anyone looking at that would have no hint what the significance of x and y are.
Best practice is to name these things to increase clarity, consistency and
brevity.
that you avoid because computers generally are not good at judgement
calls. For example, you could streamline HTML so that whenever you see
a <p> tag, you start a new paragraph, no close tag needed. That might
work most of the time, but that would prevent you from one element
inside another, as the computer could not know if you meant the new
A human designer might be able to tell what you meant from the context,
and knowing that mistakes choose the one she thinks is best suited in
that case. A computer, on the other hand, has difficulty with a task like
that, so it is helpful to use a close tag that matches the open tag to make
<p>
</p>
The old lady pulled her spectacles down and looked over them about the
room; then she put them up and looked out under them. There was a slight
noise behind her and she turned just in time to seize a small boy by the slack
of his roundabout and arrest his flight.
A human reader could easily detect that two paragraphs were intended and that the
writer probably just forgot to terminate one and start the other. The computer, on the
other hand, will only see one paragraph and layout accordingly.
On the other hand, you might think that since a computer always knows
exactly what tag it is working with (eidetic memory), you could provide a
sort of "universal close tag" that doesn't specify the type that it's closing. It
would know to close the current tag. While that's technically true, it's handy
to have the close tag there for people reading the code. It makes it easier
to remember what tag it is closing. We humans can get confused trying to
But there are other ambiguities to consider. For example, when a browser
receives a file, it may know that it's receiving an HTML file, but it won't
know which version of HTML is used (it matters). That's why the first
thing you need in any HTML file is a tag to tell you that what type of HTML
file it is:
1. <!DOCTYPE html>
In other words, the first thing the browser sees is the declaration "This is an
HTML5 file, in case you were wondering". It may seem tedious to put this at
the top of every file, but believe me, it used to be worse. You probably
noticed that it doesn't say "!DOCTYPE HTML5" but just "HTML". HTML5 can
do this because all the previous versions were much more long winded.
For example, at the top of an HTML 4.01 page, you might have something
like this:
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
We do not need to go into the details of why and what that means, just be
Everything in HTML
It may seem redundant, but the next bit tells the computer where the
1. <html>
Nearly every HTML document has two parts. The 'body' is the main content
of the page, containing text, images, tables and so on. The 'head' comes
before the 'body' (on top?). It is where you put information about the
document that does not really go in the body, AKA 'meta-' information.
Things like what kind of character set is it using, where it can find style tips
and what is the title of this page as the browser sees it (which might be
different from the title the user reads) all go in the <head>. If you have
been paying attention, you should be able to create a very basic file, in
the right form, without any content. Hint, for the head of the document
1. <head>
2.
3. </head>
You may recall the paragraph tag <p> that we used in the example above.
Try inserting a paragraph into the body of your new document. You
<!doctype html>
1. <html>
2. <head>
3. </head>
4. <body>
5. <p>
6. As my English teacher used to say, 'One sentence does not a paragraph
make'!
7. </p>
8. </body>
9. </html>
Basically, all the characters are stored in computer language and a character
encoding is the awesome dictionary that is going to help us decode this
computer language into something we can understand. In technical terms, it is
what is used as a reference to map code points into bytes to store in computer
memory; then when you use a character in your HTML, the bytes are then read
back into code points using the character encoding as a reference.
When you code in HTML, you must specify the encoding you wish for your page
to use. Providing no encoding or the wrong one is pretty much like providing
the wrong dictionary to decode. It can display your text incorrectly or cause
your data to not be read correctly by a search engine. A character encoding
declaration in your HTML is also important to process unfamiliar characters
entered in forms by users, URLs generated by scripts, etc.
You should always use the Unicode character encoding UTF-8 for your
web pages, and avoid 'legacy' encodings such as ASCII, Windows-1252 and
ISO-8859-6 mentioned above. Do not use the UTF-16 Unicode encoding either.
We recommend using the first one because it is much less complicated. You
should also always use 'utf-8'.
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. ...
6. </head>
7. </html>
Before we learn what HTML character references are, let's look at how the
Did you notice the <html> tag is missing in your output? In this case, your
you want to use these characters in your HTML, you need to use character
number.
If you want to use a named character reference in your source code, use an
ampersand symbol '&', followed by the name and a semi-colon. Names are
There are two types of numeric character reference: ones that use decimal
numbers and ones that use hexadecimal numbers. In each case, the
If you are using a decimal number, use an ampersand symbol '&' , followed
 
If you are using a hexadecimal number, use an ampersand symbol '&' ,
colon.
 
The five special characters listed in the table below should always be
Entity Entity
Symbol Usage
Name Number
Non breaking space ' ' - If you add multiple spaces, the browser will remove all
 
space that will not create   but one. So you have to use this entity to add multiple
;
a new line spaces in your HTML page.
Link to a another section on the same page
using id of the element: <a
href="#timetable">
<img src="images/test.png">
<img src="images/test.png">
Some tolerant browsers will allow using the '&' character directly
but not all. So you should use its character reference & . Check
when you notice that the browser produces the expected result anyway, it
is best practice to use character references for these five special characters
using < , > , " , & and at all
times. This is because you can never be sure what browser or application
will be used to view your code, and how that will behave.
marks within attribute values. Let's say you want to add a title attribute
the code below in a browser and hover your mouse pointer on the text
'HTML5', it will show you the title text (it works like a tooltip). The title text
in the source code includes quotes (around the number 5) like this:
currency symbols
copyright, trademark and registered symbol
general punctuation
arrows
mathematical symbols
Greek letters
Apart from the characters used for HTML syntax (described in the previous
unit), there is usually no need to use character references to represent
characters. All browsers are built using Unicode internally, which means that
they are capable of handling all possible characters defined by Unicode. So, the
best practice for symbols like copyright, currency symbols, math and arrows is
to simply type them directly into the source code.
You can do this directly in the code: <p>This is © 2015. Breach will entail a
fine of € 400</p>
There is no need for the © or € HTML character reference if you are
able to type the character itself.
If you'd like to read more information about when to use character references
and when not to use them, see Using character escapes in markup and CSS.
Learning from the mistakes others have made
There are sometimes arguments about which are the best practices. New
techniques are discovered, new ideas are born, and sometimes, fashions
change. For our purposes and the duration of this course, when we use the
term "best practice" you can trust that it is, even though we may not be able to
explain it at that point in the course, so you'll want to make it a habit.
Do's and don'ts
The history of Web pages is such that
browsers tend to be very forgiving of
certain types of mistakes. If you miss a
closing tag, it will often work the way
you expect. It probably won't crash, or
ignore the document, or give up
completely, but it might not appear
quite the way you meant it to. Or
maybe it does look like you want, but
you do not want to depend on
that. Best Practice would be to do it properly, and not depend on the browser
to patch it for
Because an HTML file essentially represents a tree structure, the open and
close tags should always match, and there should not be any overlap with
other elements. That is, you can have an element that is enclosed in another
element, or you can have two elements side-by-side, but you can never
have a situation in which part of an element is in another, but the other part is
not.
1. <p>This is a <em>paragraph</em></p>
2.
3. <h1>Paragraph ahead</h1>
4. <p>And here it is.</p>
The two examples above are fine because in each case either an element is
wholly contained in another (<em> in <p>) or they are completely separate
(<h1> and <p>). This, on the other hand, is not valid:
What is what we call "undefined". That just means that there is no telling how
the browser will decide to handle it. It might decide to automatically close
the <p> when it sees another close tag, or it could complain about an
unexpected close tag at the header. Then it might complain again when there
is a now unexpected close </p> tag.
If you played around with the minimal HTML file from the previous section, you
might have noticed that you can get more minimal than that. For example, if
you take out the "head" section completely, the browser will still render the
page without complaint (at least Chrome will; Firefox does complain in the
debugging console, but we will save that for week 4). In fact, you can even take
out the "body" open and close tags (not the content, of course) and it will still
work as expected. Not only that, if you take out the <!doctype> statement, it
still works (and Chrome still doesn't complain!).
What's actually happening is that the browser knows roughly what to expect in
an HTML page, so if it sees a file ending in '.html' it will automatically stick
some stuff in if it is not there already. It will typically make basic
assumptions It is an HTML5 file, everything in there is content, so it goes in
the <body> section, the <head> section is empty. If you right-click on an
element and choose "Inspect", you will see that the browser has included
the <html> section containing the <head> and <body> sections, even
though it wasn't there in your file.
Note that we said "typically". The current behavior of most browsers will handle
this, but it is "undefined" so there is no guarantee that next update won't
break it. To be correct and complete, you need the <!doctype> section and
the <html> section with <head> and <body>. In any case, it is a good idea (best
practice).
Proper indentation is one way to make your code clearer and easier to
understand:
1. <body>
2. <h1>Here is a heading</h1>
3. <p>
4. <ol>
5. <li>List Item 1</li>
6. </ol>
7. </p>
8. </body>
The code above doesn't give any sense of the structure of the document. By
using indentation effectively, you can make it more clear, showing the nesting
of elements:
1. <body>
2. <h1>Here is a heading</h1>
3. <p>
4. <ol>
5. <li>List Item 1</li>
6. </ol>
7. </p>
8. </body>
Often projects will have coding styles that everyone is expected to use so that
everything looks consistent and developers can more easily read others code.
If you are creating the project, you can decide what the rules are (how many
spaces to indent, single or double quotes etc.) but unless there is a good
reason to change away from typical practices, it is usually best to adopt them.
It might seem confusing at first, but this rule about white space is actually very
convenient. The third option might be a bit too cramped for your taste, while
the second might seem to take up too much room in your source code.
Because it doesn't matter to the browser how much white space there is, you
can use white space to make your code more visibly organized and easier to
read (note the use of indentation in the second <H1> element above).
Given that tag names are case insensitive (you can write them either way), you
might think that everything in between < and > is case insensitive, but it is not
that easy. We have not learned much about attributes yet, but when we do we
will discover that they are "case sensitive", thus these two elements will have
different 'id's:
1. <p id=ThisOne>
2.
3. <p id=thisone>
Even though they're spelled the same, the differing cases indicate different
names. Note that distinguishing different ids solely by case (i.e. spelled the
same but with different capitalization) is a really bad practice (opposite of best
practice). Instead you can use capitalization in other ways, like CamelCase.
.... are all equivalent. It is also important to know that, in HTML, double and
single quotes are almost interchangeable, but they have to match. If you start
a string with a double quote, the computer will not end it until it sees another
double quote. Any single quotes will be happily considered part of the string,
which is handy if you need quotation marks in your string. Because of this, if
you create a string as ' "quote" ' (single quotes containing a double quoted
string), your string will have the letters <space>-"-q-u-o-t-e-"-<space> (with
double quotes in the string and spaces outside those) as opposed to "quote"
which will just have the letters q-u-o-t-e (no quotation marks or spaces in the
string). Nevertheless, best practice is to be consistent in your quotes, so it's
best to quote them all the same way, even if the browser would understand it
anyway.
In summary:
The idea is to take advantage of these flexibilities to create clean organized
code that is easy for a human to comprehend. I guess you could sum it all up
with these simple dictums:
Case matters, except when it doesn't - case matters for some things, like
strings and attributes, but not others, like tag names.
White space is ignored, except when it's not - White space is used to
separate things, but adding more than one space will be the same as just one.
White space in strings is always just as you type it.
Quotation marks are not part of a string, except when they are -
Quotation marks enclose a string, but thanks to the flexibility of choice
between single or double quotes, it is easy to include one or the other in your
string.
The important thing is to look good - You can take advantage of flexibility
in capitalization and white space to make your code more readable and
organized.
Are they consistent with each other? Are there some rules that don't seem to
make sense?
Can you find other style guides or coding standards that agree or disagree with
some of the suggestions in one of these guides?
Try "Direct Input" and type some HTML5 code with errors to
see what it detects.
Using "Validate by URI", try some popular Web sites and see
if you can find any errors.
Tags we have already used
Now you can create a simple, empty, HTML page, and you know what tags are,
though we have not said a lot about specific tags, what they mean, how many
there are, etc. We will start with the ones we have already seen:
<!doctype> - This tag is special. In fact, many folks don't even consider it a
tag, as it is officially the DTD - Document Type Declaration. Unlike most tags, it
has no closing tag, not even a "/" at the end. It is there to declare exactly what
type of HTML the computer will find in this file.
<html> - The html open and close tags wrap around nearly everything in your
html file (except the doctype tag). This essentially contains all of the
HTML code in the file, which is generally everything (one big html element).
Next week we will learn about attributes, and you will learn that you should
always add a lang attribute to the html opening tag, to identify the default
language of your page.
<head> - The head element is where you put information that does not really
appear in the body of the work. For example, the <title> of the page, which
typically appears on the window containing the page, is defined in the head
section.
<body> - The body section contains all of the content of your page, essentially
what the user sees. This could be text, pictures, links, videos, tables and so on.
In addition to the content, the body usually contains lots of other elements,
each indicated by their own tags.
<h1> - There are a whole collection of 'h' tags, <h1>, <h2>, <h3> . . . all the
way up to <h6>. Why there are 6 rather than 5 or 7 may be a bit of a mystery,
but there it is. They're generally used the same way you would use chapter or
section headings in a book (don't confuse the h here with the <head> section,
that is completely different). An <h1> tag might be used as the title of the
document (as it appears on the page, not the same as the
aforementioned <title> element), or to indicate the outermost level in a
group of nested sections.
Though you theoretically should not think about what it looks like, it
will typically appear as large, possibly bold text in your document, to mark a
separation or beginning of some new section. <h2> is usually a bit smaller,
and <h3> smaller yet and so on down to <h6>. This allows logical nesting of
sections, though they should not be nested too deeply. Try not to skip levels of
headers when nesting them. Headings are really useful for some assistive
technology users and missing levels can be confusing.
<p> - P is for 'paragraph', which is how much of your text information might be
arranged. Depending on the style you are using, text wrapped in a <p> tag
may be indented or have extra vertical white space before starting. When
rendered on the web page, a p element will typically be a new line.
You might notice that when discussing how these different elements are
rendered (i.e. what they look like to the end user) you will find words like
"typically", "possibly", and "generally". It is a little picky; as you will learn in
Week 3, it is possible to change the styling of one element to look like just
about any other element. You could style a <p> element so that it looks like
an <h1>, though best practice would be not to do that.
<ul>, <ol> - These two tags are used to indicate a list of things. The only
difference is that <ol> is an "ordered" list, meaning the elements are in a
particular order, and it might be a good idea to number them. The
"u" in <ul> stands for "unordered" and is used for a list of things where the
order doesn't really matter, so it is usually rendered as a bulleted list, or
something else without numbers.
<li> - The li element is a "List Item", i.e. one item in the list. As you might
expect, this element only really makes sense nested inside a list
(<ul> or <ol>). In the final rendering, each li element would typically be
preceded by a number or bullet, or something similar (but not necessarily).
Thus a list in HTML would be look something like this:
1. <ul>
2. <li> First item in list </li>
3. <li> Second item in list </li>
4. ...
5. </ul>
<hr> - This one might be debatable. HR originally stood for "Horizontal Rule",
i.e. a horizontal line across the width of the text. It's still there in HTML5, but
now is officially supposed to represent a "thematic break" in the content. It
would typically look like this:
<br> - This one signifies a line break. It is used for any number of purposes.
For example it can be an easy way to make sure that lines of poetry break
where they're supposed to (less verbose than requiring each line to be a
separate element). Essentially it helps break the "white space" rule, where
spaces and carriage returns are generally treated the same, the <br> tag is
treated as a required carriage return. Because it's an empty tag (doesn't
contain any text or anything, just indicates a particular point in the text), it
doesn't really need a close tag, so it can be written as <br>, though <br /> is
also acceptable. Oddly, in the browsers I tried, if you do add a close tag, as
in <br></br>, the close tag is interpreted as a regular br tag, thus you get two
line breaks in a row. One other thing to remember is that the <br> tag implies
a break even if there is no break in the text containing it, i.e. these two
sentences would be formatted exactly the same:
These are HTML, CSS, and JavaScript code editors that preview/showcase your
code bits in your browser. It helps with cross-device testing, realtime remote
pair programming.
This week, we'll start off with a simple first draft using just what we've learned
about HTML5 using tags we've covered. We want to have the following
components:
A large title for the app, something like "My Favorite Recipes", or whatever
you'd like to call it.
A description of a recipe, just some plain text explaining what the recipe is and
any other pertinent information.
A set of steps to follow, numbered in order.
You will find below a video that explains step by step how to start your recipe
project, using Intel XDK.
If you want to share your work/recipe in the discussion forum, please either
copy-paste your lines of code into a JSBin or a CodePen project, or write your
HTML5 code directly into one of these online tools.
Week 2 - Content
2.1 Introduction: Check out this video explaining what you'll be learning
about in Week 2 - and wrap your mind around the concept of "semantic
markup".
2.2 Attributes: Here you will build on to what you have already learned
about attributes.
2.4 Images: Learn how, when, and where to best utilize images in your Web
pages.
2.5 Hyperlinks: The connections that allow the world to jump from place to
place on the Web, explore the secrets of this powerful mechanism.
2.6 Exercises - Week 2: Lets check what you've learned during Week 2.
Tags and elements are building blocks of HTML5. However, they can be made
so much more exciting with attributes. Let's take a simple element like list. You
know how to add one to your page but can you change the order of your list?
Or change it to an alphabetically ordered list instead of a numerical list? Can
you display your list in reverse order? Yes, you can do all this and more using
attributes.
Apart from exploring attributes for elements, we will continue to add life to our
Web page by adding images and hyperlinks and learning about how to use and
place them properly in your Web page.
This week we will also look at creating meaningful Web pages. Imagine you are
the Web page designer of an online magazine. You want to have a central
article, some aside commentary, captions, a summary of your article,
addresses and citations. You also want to provide more detailed information
such as, 'This sentence is really important and you need to convey that to the
reader'.
If we just use <p> tags and header tags, <h1> to <h6>, visually it might look
like what you want, but only a human will be able to read and understand the
page. To a browser, there is very little information except that there is text and
headings in your page. How can a search engine know what is important? Does
a visually impaired person have to listen to the entire page or can just jump to
the article?
It is very important to style your Web pages for search engines to improve your
SEO rankings and for visually impaired people who access your Web page
using assistive technology like screen readers. Semantic markup enables all of
this and more.
Introduction to attributes
We learned a little bit about what attributes are in the previous week. Let's
1. <ol>
2. <li>Lights</li>
3. <li>Camera</li>
4. <li>Action</li>
5. </ol>
Output:
1. Lights
2. Camera
3. Action
default.
1. <ol start="5">
2. <li>Lights</li>
3. <li>Camera</li>
4. <li>Action</li>
5. </ol>
Output:
5. Lights
6. Camera
7. Action
Here using the start attribute, we made our list start with 5 instead of 1.
Like start, we have many useful attributes we will see in this section that
can affect your element. Attributes are a significant part of HTML. Tags and
Syntax:
It is used inside the opening tag it is applied to and should be added after a
space from the tag name: <ol start="5"> . The start attribute is
start="5"
Attribute name, equal sign, opening quotes, attribute value, closing quotes
name - start
attribute'. These attributes have only two types of values - true or false. But
instead of writing "true" or "false" for its value, you add the attribute name
<ol reversed></ol>
<ol start="5"></ol>
<ol id="cinema" class="attribute-list" start="5"></ol>
<ol start="5" class="attribute-list"></ol>
Your task is to make the text color of the first paragraph red and the
other blue. How do we do that? You add styling to your HTML document
through CSS. CSS is a style sheet language where you add any
presentation related information for your HTML document. You will learn
about this in the next chapter. In this case, you will have to write code in
your style sheet to inform that it needs to change the text colors
respectively.
But to identify each paragraph, we need to give them each a name first so
we can instruct our style sheet to make X red and Y blue. This unique name
we give each element is called an 'ID'. This is very similar to your school or
corporate ID that is unique to you. No one else in your company will have
because we know that two people having the same ID will just cause a lot
of confusion.
one you will be using very frequently. Let's assume you are an author of a
book. You like poems and you want to include at least 20 of them in your
new book. You add IDs for them: 'poem1', 'poem2', 'poem3'.
You want your poems to look different from your other text. Grey text color,
If you use id attribute, you can instruct the stylesheet to style each poem
in a particular way. It will look something like (we will learn how to write
proper styles in the next chapter, so for now we will just phrase it in
English) -
instruct it to do the same thing 20 times for different poem IDs? HTML
makes it easier. We use the class attribute. Let's name this class of
poems 'poetry'.
So now, all you have to do in your style sheet, is to instruct it to make all
Global
Non-global
Global attributes
Global attributes can be applied to all tags. They are common attributes.
Examples of global attributes are idand class. There are more global
attributes. Here is a list of all the global attributes and the values they accept.
<ul id="intro-list"></ul>
<pre class="html-code"></pre>
Non-global attributes
Non-global attributes are attributes applied to a specific instance of a tag. It
can be applied to one or more tags. For example, start is an attribute for
the <ol> tag and it cannot be applied on the <p> or <h1> tags, it is specific to
only ordered lists - <ol>. Another attribute specific to the <ol> tag
is reversed, which we learned in the last unit as an example of a boolean
attribute. The non-global attribute width can be applied to several tags such
as <img>, <input> and <video>.
1. <ol>
2. <li>HTML5</li>
3. <li>CSS</li>
4. <li>Javascript</li>
5. </ol>
1. <ol reversed>
2. <li>HTML5</li>
3. <li>CSS</li>
4. <li>Javascript</li>
5. </ol>
Ordered lists have their own specific attributes and all global attributes can
also be applied to them.
More examples:
The image <img> and hyperlink <a> elements, which we will be learning about
shortly, have many non-global attributes of their own.
Other than the common global attributes, if you wish to learn about the
supported non-global attributes for any element, you can visit the W3C
HTML5 recommendation or the HTML attribute reference available at
Mozilla Developer Network (MDN).
Important: Throughout the course, using the MDN attribute reference, you are
encouraged to explore non-global attributes for the elements you learn about
or would like to use in your . In the MDN attribute reference list, you can click
on the element's hyperlinked name to be navigated to its page that lists
supported attributes for that element.
Like we saw in the previous unit, here is a list of all the global
attributes (or here) and the values they accept. To understand attributes,
NOT the same. That does not mean you can use two different IDs that
only differ by case, i.e. "myid" and "MyId". They are different and so legal
1. Styling your element. You can specify the style you want for the
Using CSS, you can specify code that will give different styles to
this section. You can link to a section of your HTML page using the 'id' of
the section. You should reference the 'id' value with a number sign
preceding it - '#id-value'
1. <a href="#introduction">1.1 Introduction</a> <!-- This is a hyperlink
element which we will learn about later in this week -->
2. <p id="introduction">This paragraph is the Introduction to the
webpage</p>
the 'id' of the element, you can write JavaScript code to make it perform an
The class attribute, while similar to id, groups a set of elements in the
is unique to the element, the same class name can be assigned to more
For example:
Both paragraphs above are grouped under the class named 'question'. An
element can have one or more class names. If we also want the second
question to be under the 'html' class because it is a html related question,
1. Styling your elements. You can specify the style you want for all the
In your CSS, you can include code to style your classes like this:
I am the author
Yes
The 'Do you like HTML5?' question has styles for both classes 'question' and
The lang attribute indicates the language of the text in the element to
characters, rather than Chinese shapes – but only if you have told it that
knowledge of the language of the content: for example, CSS will style
Multiple subtags are separated by hyphens. (Do not use the ISO lists of
languages and countries! Those lists are already subsets of the IANA
<html> tag. You can also declare the language of content within the
For example:
1. <html lang="en-GB">...</html>
2. <p>In French you'd say <span lang="fr">On voit souvent des chats sur
le Web.</span></p>
The first example above shows how you can qualify the language (English)
with a region subtag (GB) to specify British English. This distinction can
be useful for spellchecking your source. You can also add other subtags,
such as scripts and variant labels to further refine the language, however,
the golden rule is to always keep the lang value as short as possible, and
only use additional subtags when you have a good reason (ie. use just ja for
Japanese, not ja-JP). For more information, see the article Declaring
language in HTML.
The second example shows how you could specify a change of language
within the document. This would help a voice browser pronounce the
French word 'chats' correctly, meaning 'cats' and not 'chats' in English.
Try this: Place your cursor on the word and then on the picture below.
NASA
Did you see the two secret messages? A message that appears when you
value.
MDN Attribute
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
Activities - Attributes
Please find below suggested activities to help you practice:
1.Find the list of supported attributes for the <area> tag. (Hint: use the W3C
cheatsheet or MDN attribute reference list)
2.Create two paragraphs with the same id and run your code in Intel XDK. You
can view your output in a Chrome window. What happens? We know the value
of the id attribute must be unique, so why does it behave the way it does? Run
your code through the W3C Markup Validator. Does it throw an error?
3.Does an attribute called src exist? What is the purpose of this attribute and
what are the elements it can be applied to? (Hint: refer to the W3C HTML5
specification, W3C cheatsheet or MDN attribute reference list)
4.Create an ordered list starting with the number 11. Then, reverse the list.
Give it the following title (when you hover your mouse, it should display the
title as a tooltip): 'Activity List'.
Note: If you wish to share your HTML code in the discussions, you can paste
your code directly in a discussion forum post (highlight code and Ctrl+K/use
the code widget) or use one of the following online code editors:
JS Bin: http://jsbin.com (JS Bin tutorial)
CodePen: http://codepen.io (CodePen tutorial)
These are HTML, CSS, and JavaScript code editors that preview/showcase your
code bits in your browser. It helps with cross-device testing, realtime remote
pair programming.
Let's look at a few interesting tags that lived as exception to this rule and
This is how the above HTML code will look in a browser (go ahead and try
it!):
It seems redundant for two tags to do the same thing in HTML.
While <b> and <strong>, <i> and <em> seem no different in a regular
The four tags we saw above can be categorized into style and semantic
tags.
talked about how the text should look like on the screen.
tags said something about the semantic of the tag. It offered meaning.
Emphasizes text
Semant
<em>
ic Text is italics by default in a
browser
Important text
<strong Semant
> ic
Text is bold by default in a browser
<b> vs <strong>
Bold is a style that makes letters thicker so it stands out among other
text but it has no semantic meaning, for example for voice browsers,
screen readers, and other types of ways to access the Web. A device
like Kindle Paperwhite that renders text differently, might not pick up the
bold.
instructions on how the text should look in the case of <b>. It represents
importance or seriousness.
<i> vs <em>
shows etc. Just like the bold tag, since it is meant purely for presentation
sentence you emphasize can change the whole meaning. Try reading the
sentences below out loud, stressing on the emphasized words: 'you' and
'store'.
Changes in HTML5
So far, we have looked at how these tags were in HTML4. In the beginning
of this unit, we learned that content and style should be kept separate
and that styling should be kept tucked away in Cascading Style Sheets. So
how did <i> and <b>, purely style elements make the cut?
As of HTML5, <em> is now also used for words and sentences you would
You should also bear in mind that <b> and <i> may not produce
appropriate styling for some parts of the world. For example, Chinese
underlining to bold, because bold makes it too difficult to read the text.
If you do use <b> or <i> tags, the HTML5 specification recommends that
you also use class attributes to identify the semantic intention of the
markup. This can be particularly important for pages that get translated,
across different cultures. For more information, read the article Using
If you want to add a paragraph, you would use the paragraph tag. If you
want to add a heading, you would use the header tags <h1>-<h6>, and to
add an image, you would use the image tag (we will learn about this later
this week). All these tags along with their id and class attributes are
semantic because they suggest the purpose of the content within the
tags. <i> and <b> suggest nothing about the content and this is why they
From a semantic HTML perspective, using the right tags is important. You
should use <blockquote> to wrap a quote and not use a paragraph tag
and then style it to look like a quote. You should use <em> to emphasize a
part of your content, not just to italicize text. For presentation purposes,
you can achieve the same using CSS. How something looks has very little
to do with what it means. This is why in HTML, we separate content and
style.
Why is it important?
Semantic elements are beneficial to both the developer and browser. They
convey much more information about your HTML document's content and
structure. There is a tag called header in semantic HTML. When you see a
heading like <h1> or <h2>, you know this is likely the start of a new sub-
language.
understand the markup structure better (when you come back to your code
after a year or pass it on to a colleague, this is going to help you and them
a lot!). For the browser, it can better differentiate different types of data
Since its establishment, W3C has worked hard to make HTML as semantic
browsers making life easier for them. It also improves the accessibilityof
We can apply the elements in the image above to a simple Web page like
this:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Intel® XDK</title>
5. </head>
6. <body>
7. <header>
8. <h2>Using Intel® XDK.</h2>
9. </header>
10. <nav>
11. <!--You will learn about <a> tag later in this chapter-->
12. <a href="">Launch Intel XDK</a><br />
13. <a href="">Create a project</a><br />
14. <a href="">Write HTML</a><br />
15. <a href="">Test HTML</a><br />
16. </nav>
17. <section>
18. <h3>Launching Intel XDK</h3>
19. <p>This section is about launching Intel XDK...</p>
20. </section>
21. <section>
22. <h3>Creating a project</h3>
23. <p>This section is about creating a project in Intel XDK...</p>
24. </section>
25. <article>
26. <h3>Can I use an external editor for development with Intel
XDK?</h3>
27. <p>Yes. You can open your files and edit them in your favorite
editor.</p>
28. </article>
29. <aside>
30. <h3>Editing</h3>
31. <p>Intel XDK uses the open source Brackets editor.</p>
32. </aside>
33. <section>
34. <h3>Testing</h3>
35. <p>View your HTML code using Live Layout Editing in a Chrome or
Firefox window.</p>
36. </section>
37. <footer>
38. <p>Written by: HTML5 Developer</p>
39. <p>Contact
information: <ahref="mailto:[email protected]">html5developer@tes
t.com</a>.</p>
40. </footer>
41. </body>
42. </html>
New HTML5 semantic elements
Semantic
Description Example
Element
<header>
Introduction for the whole page or individual <h1>The Importance of Being
sections, article, nav, aside elements. Earnest</h1>
<header> Typically contains site name, logo, <h3>A Quest for Truth and Beauty</h3>
navigation. Does not have to be at the <p>The play was written in 1895 by
beginning of page. playwright Oscar Wilde</p>
</header>
<footer>
<p>Written by: Oscar Wilde</p>
Includes typical footer information like
<p>Contact information: <a
<footer> authoring, copyrights, contact information
href="mailto:[email protected]">
and a footer menu.
[email protected]</a>.</p>
</footer>
<nav><ol>
Navigation links for the document. A page <li><a href="/act1/">Act 1</a></li>
can have more than one <nav> element like
<nav> <li><a href="/act2/">Act 2</a></li>
table of contents, horizontal navigation in
header and footer navigation. <li><a href="/act3/">Act 3</a></li>
</ol></nav>
<section>
Defines sections in the document such <h1>Act 1 - Scene 1</h1>
<section> as chapters, headers, etc. Typically used on <p>Set in the morning room of Algy's flat
content that cannot make sense on its own. in Half Moon Street</p>
</section>
<aside>
Side content other than main content, like a
<h3>Algernon Moncrieff</h3>
<aside> sidebar. These are not considered as part of
<p>A wealthy bachelor who lives in a
the main page outline.
fashionable part of London. He has a good
sense of humor and utter lack of respect
for society.</p>
</aside>
<details>
<details> A way to provide additional information that <summary>Cast Members</summary>
the user can show or hide. Content that is <p>George Washington as Algernon
*see example shown to user by default. Other content is Moncrieff</p>
below hidden and can be expanded to view. <p>Ronald Reagan as John Worthing</p>
</details>
<figcaptio
n> <figure>
<img src="img_cast.jpg" alt="The
Importance of Being Earnest Cast">
*see Provides a caption (explanation) of an image.
<figcaption>Fig1. - The cast hard at work
To be used within <figure>.
example at dress rehearsal before opening
night</figcaption>
below
</figure>
<mark>
<details> element
nested <summary> tag and some other content. The result is that the
summary is shown with a disclosure triangle alongside it, and the other
displayed to the user. This requires no JavaScript and is a simple way to get
Below we see the HTML, and you can try it out for yourself! Note that
Result / Try
HTML
It!
1. <details>
2. <summary>Cast Members</summary>
3. <p>George Washington as Algernon
Moncrieff</p>
4. <p>Ronald Reagan as John Worthing</p>
5. </details>
See also the current browser support (on caniuse.com).
<figcaption> element
(figure). While the alt attribute explains the image for assistive
technology, <figcaption> can be used to provide additional information
1. <figure>
2. <img src="img_cast.jpg" alt="The Importance of Being Earnest Cast">
3. <figcaption>Fig1. - The cast hard at work at dress rehearsal before opening
night</figcaption>
4. </figure>
Result:
<mark> element
Most browsers will display mark element with a yellow background to black
text by default, however, if it doesn't, you can specify the styling in CSS.
Effect of semantic elements
If you have had a chance to try the examples of the semantic elements
discussed above, you will notice that semantic elements are not visually
change to the document. The rest don't do anything except providing the
A good example is <aside>. The <aside> element is used for side content
other than the main content, such as a sidebar, but it does not actually
create a sidebar in your page. Sidebar is a user interface (UI) element and
must be styled to achieve the look of a sidebar. The following code will
Note: This section is optional material included for the curious. It will not
We will look at a few more semantic elements that are commonly in use
<address>
<a
href="www.example.com">John
Used to supply contact information for its
<address> Doe</a><br>
nearest <article> or <body> ancestor.
#123, Doe Villa<br>
Los Angeles, USA
</address>
Apart from these, <cite>, <em>, <strong>, <p> and <blockquote> are
Now you have learned the semantic elements available and their syntax.
When you try to apply it practically, there are some common problems you
might run into. For example, when do we use <header> and when do we
Fear not. We will discuss these scenarios in detail so you can be better
page. It can contains headings, paragraphs, tables, images, logos and even
course. <h1> is for the most important heading and <h6> is for the least
For a simple HTML page, we will use the W3C HTML5 specification. You
If you view page source on the W3C specification and do a search for
'<header>', you will be able to view the contents of the header element.
1. <header>
2. <!-- You will learn about the <a> and <img> tags later in this chapter-->
3. <p>
4. <a href="http://www.w3.org/"><img alt="W3C" heigh
t="48"src="http://www.w3.org/Icons/w3c_home" width="72"></a>
5. </p>
6.
7. <h1>HTML5</h1>
8. <p>A vocabulary and associated APIs for HTML and XHTML</p>
9. <h2>W3C Recommendation 28 October 2014</h2>
10. </header>
Like in the example above, the header can and frequently does contain
1. <body>
2. <h1>Brad's Cookbook</h1>
3. <h2>Slowcook Recipes</h2>
4. <h3>Minestrone Soup</h3>
5. <h4>Description:</h4>
6. <p>Minestrone Soup is a simple and nutritious dish...</p>
7. <h3>Refried Beans</h3>
8. <h4>Description:</h4>
9. <p>Cumin is the secret to this recipe.</p>
10. <h2>Dessert Recipes</h2>
11. <h3>Peach Cobbler</h3>
12. <h4>Description:</h4>
13. <p>If you can't get fresh peaches, frozen to the rescue!</p>
14. </body>
Assistive technology uses heading markup, <h1> to <h6> to identify
structure, a screen reader that parses your Web page will in some manner
indicate the heading level. For example, raise its voice to indicate higher
level headings or announce the heading level with the text it reads. They
can also navigate through the headings quicker making it easier for the
You can learn more about the source of this technique in that other
resource page.
Can you have more than one <header>, <footer> and <nav>?
There is a common misconception that a Web page can only have one
header at the start, one footer at the end and one main navigation section
Header and footer elements are for the parent element (section, article,
division or body) that they are used in. If you have multiple sections or
articles, then you can have one header and footer for each.
Header and footer elements can also be used site-wide at the top and
bottom of the body of the Web page. This type of header will typically
contain logos, main heading, a search area and site-wide navigation and
the footer will typically include authoring information, references and other
Sometimes, the header of a Web page comes from a template file. This
header
and footer.
If you visit the page and navigate to other parts such as Product Support
and Documentation, you will see that the header and footer remains
unchanged.
Multiple navigation menus
So we know we can have the nav element in header. In the Intel XDK
example above, we have one in the global header with menu items
'Development', 'Tools' and 'Resources'. Did you notice that we also have
one in the footer? With menu items 'Support', 'Terms of Use' etc. You can
definitely have more than one navigation menu in your Web page because
there are so many different types of menus calling the need for
multiple <nav> tags. Using <nav> also helps assistive technology. Screen
readers now knows exactly where page navigation lies so it can provide
options for the users to either skip reading its contents or to make it
immediately available.
Complete example
Now, let's look at a more complete example using a global header and
utm_source=website&utm_medium=embed&utm_campaign=y3adugze
article out of a Web page, it should make sense all by itself. In Brad's Blog
example in the previous unit, if you extract only the first article, you can
see that it will make sense all by itself without any context. It can be reused
anywhere else.
1. <article id="ces">
2. <header>
3. <h2>CES 2015</h2>
4. <h3>Consumer electronics and consumer technology tradeshow</h3>
5. </header>
6. <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam neque
risus, consequat eget vestibulum eu, consequat at eros. Nam eu nisl vel neque
malesuada sollicitudin quis eget libero.</p>
7. <footer>
8. <p>Written by guest author Nicholas Abc. Read Nicholas's blog here.</p>
9. </footer>
10. </article>
One article element can be nested inside another. For example, if you have
a blog post and you want to include a forum post or newspaper article in it,
1. <h4>Getting There</h4>
2. <p>Arriving at the show location proved much harder for me. I couldn't
get a hotel closer to where the show was taking place and so had to rent a
car....</p>
3. <h4>Conference Sessions</h4>
4. <p>I managed to squeeze in 3 conference sessions on the first
day...</p>
This doesn't look like it makes sense all on its own. So we can't put it into
fact, all content within the body element is considered to be within one
section. Sections can be nested (one section in another). Sections can also
be part of an article, aside or nav elements. While the code above makes
An article element can use section elements to split its contents into
groups.
Semantic elements sample in Intel® XDK
- www/index.html.
If you are not using Intel XDK, you can still access this sample.
It should only be used if you cannot use any other semantic element in its
place.
1. <section>
2. <h2>Week 1</h2>
3. <p>This week, you will be learning about...week 1 stuff</p>
4. <div class="code">
5. <ol>
6. <li>Line of code</li>
7. <li>Line of code</li>
8. </ol>
9. </div>
10. </section>
11. <section>
12. <h2>Week 2</h2>
13. <p>This week, you will be learning about...week 2 stuff</p>
14. <div class="code">
15. <ol>
16. <li>Line of code</li>
17. <li>Line of code</li>
18. </ol>
19. </div>
20. </section>
If you want to style all code snippets in your HTML document a certain way,
you can place your code in a div container and apply styles collectively to it
using the class attribute.
I want to change the color of only 'ABC Company'? Should I use a paragraph
tag? Let's try that..
If you then design your style such that the 'company' class will make text blue,
the output will look like this:
ABC Company
That does not work because <p> splits it into a newline. The HTML above is also
invalid. We will see why shortly. Now, let's try <span>.
Like <div>, <span> is not a semantic element. You should only use <span> if no
other semantic element is appropriate. <div> and <span> serve the same
purpose but should be applied at different levels. <div> is a block level
element (for a block of space) while <span> is an inline element (for within a
line or phrase).
Block level elements - used within body of the page. It occupies a block of
space and starts in a new line. It usually has an empty line above and below
the block. They can contain inline elements and other block level elements.
Other examples: <p>, <h1> - <h6>.
Inline elements - as the name suggests are 'in-the-line'. They can start
anywhere in a line. They can only contain data (like text) or other in-line
elements. Other examples: <em>, <strong>.
After an opening tag <p>, if it sees another <p> or any other block level
element including <div>, it will automatically close the first open <p> for you.
Nesting one paragraph tag in another is not valid because the browser will
consider them as two paragraphs one after the other. Even though you close
the paragraphs with two closing tags </p></p> at the end, they are ignored as
errors.
These are HTML, CSS, and JavaScript code editors that preview/showcase your
code bits in your browser. It helps with cross-device testing, realtime remote
pair programming.
Introduction to images
The <img> Tag
In this age of visual culture, what is a Web page without images? Drab. Pictures
and images make everything more interesting and engaging.
The image tag has several attributes out of which only src and alt are
required. The rest are useful but optional attributes.
1. <img src="http://www.example.com/image-with-absolute-url.png" al
t="Example Tutorial Image">
The type of image file format (i.e. png, jpeg, etc.) you should use does not
depend on the img element in HTML5 but on the browser that renders the
content. Some formats like png, jpeg, gif and bmp are widely supported by
browsers and so they are recommended when using images in your Web site.
Here is a comprehensive list by Wikipedia listing browsers and the image
formats they support.
Here is a list of things to keep in mind when using the src attribute:
Image: Formats
Before you begin using images in your Web site, you are advised to
visit http://1stwebdesigner.com/image-file-types/ to get an understanding of
the most common image file types such as jpeg, gif, bmp, tiff and png, their
pros and cons, operating system compatibility, when to use which format etc.
When using images in your HTML5, there are a few image format related
information to be aware of.
Image Data - Most images, especially JPEG, contain a lot more data than is
needed for a browser and are too often overly large and slow. You can reduce
the size of the image using photo editing software that allows you to re-sample
an image to reduce its pixel data and in turn reducing image size. However,
once you re-sample an image, do not make change its size (height and width)
to make it larger as it will become pixelated and blurry.
JPEG (Joint Photographic Experts Group) images compress well and are the
standard for photos. But they don’t support any sort of animation or
transparency.
PNG (Portable Network Graphics) images support transparency and alpha
channels. This makes them useful for non-rectangular images that may need to
overlay different background colors or other elements on the page. To make
PNG images, a user would need graphics editing software (like GIMP,
Photoshop, or others). PNG is a W3C Recommendation
(https://www.w3.org/TR/PNG/).
SVG (Scalable Vector Graphics) are defined mathematically and
support animation. Also, since they are defined mathematically they scale
to any size without worrying about pixels, resolution or image data. This makes
SVG images an excellent format to use, if possible. SVG is great for charts,
graphs, maps, geometric shapes, and line based illustrations. SVG is also a
markup language in its own right and is very similar to HTML. Typically it is
created with vector graphic software (like Inkscape, Adobe Illustrator, and
others https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Tools_for_SV
G), but some people write the markup by hand. Note that SVG 1.1 is a W3C
recommendation (https://www.w3.org/TR/SVG/).
Using this attribute, you can provide a short description of what the image is
about. This description should convey information about the image or its
function in the page. The alt is an important attribute because it is the text
alternative to the image for users who are unable to see the image, instead
using assistive technology like screen readers that rely on the alt text. It is
also useful to provide relevant information for search engines.
If the image is purely for presentation or decoration purposes, you should leave
alt empty - <img alt="">. Assistive technology will then ignore this content.
Depending on the category the image fits into, the alt text differs. This
W3C WAI Images Tutorial is an excellent resource for deciding the category of
your image and for learning how to write proper alt text for that category.
Here is an example of a tulip image using invalid source (that image is missing
from the 'images' directory) and how it will look in a Web browser:
Note: For images, you must use an alt attribute as there is no guarantee that
the title attribute is presented to assistive technology
users. The title attribute should not be relied upon for important information,
and it should not be used in place of the alt attribute.
The use of these attributes really depends on how you are using the image. If it
is part of an image grid or a list with multiple images of the same size, it is best
achieved by CSS. So you don't have to bother adding the same dimensions to
every image and it will be repetitive. Plus it is generally bad practice to encode
dimensions directly into the HTML.
However, if you are adding the image into some content and it needs to be a
certain size for the visual flow of the reader, then it is best to add it to HTML
using the height and width attributes. This is to avoid cluttering your CSS with
a style for every image in your page. This is also useful if you are changing or
removing the image: you can just remove it from your HTML and not deal with
remembering to remove it from your CSS too.
Decorative images
Should all images be part of HTML content?
A significant part of images on the Web are not used for any meaning. They
merely serve a decorative purpose and fall under the presentation category.
How do you identify these images? Well, if you have nothing relevant to put in
your alt attribute or if you feel like it is not important to your or to the
prospective reader, it should not be in your HTML.
We know we should keep content and style separate in HTML. Then how do we
move these images out of content? Well, don't add them using the <img> tag in
HTML. Use CSS instead.
background images
fancy border graphics
banner graphics
pictures of landscapes or textures that are being used as elements behind or
surrounding the content
Some pages (especially for video games, fancy magazines, etc) have a lot of
eye-candy imagery that is not core to any of the semantic meaning of the
page.
Activities - Images
1.Create a simple Web page that talks about your day using only text and
images. Include at least three images and add the alt and title attributes.
2.Look through the Web and your favorite Web sites and identify those that you
think use a lot of decorative images.
3.Create a HTML page and add the following types of images:
- Informative image that represents concepts and information
- Decorative image
- Images of text
Use the alt attribute to provide alternate text for the images above.
Refer to the WAI Images Tutorial for a guide to writing alternate text.
Introduction to hyperlinks
What Are Hyperlinks?
In a typical Web page, I am sure you have seen a sentences like these:
Try clicking the blue text or the 'Buy Now!' button if you haven't already (make
sure to navigate back to the course).
Hyperlink is any text or image you can click and it will take you to another
page. This page can be:
Best Practices
Apply hyperlinks to short phrases. It is unusual to see the
link tag used around a whole paragraph.
Make link phrase meaningful. Avoid phrases like 'Click Here'
or 'Read More'. 'Click here to get help' is redundant when
you can create a link around the phrase 'Get Help'. The link
is an indication that it should be clicked.
Don't use short link text. It is easy to miss the 'blue'
hyperlink if it is used on one word or character and is hard
for users to click using touch screen.
Appearance - links have a default appearance in most
browsers, blue and underlined. Ensure no other text in your
page is underlined so as to avoid confusing the user. They
might get frustrated trying to click text that they think is a
link.
If you choose to have image links, it should have alternate
text that describes the purpose of the link instead of the
image used - describe the target link.
1. <a href="www.table-header-cells.com">
2. <img src="table-th.png" alt="Introduction to table header cells and their
usage">
3. </a>
Anchor Element
The hyperlink tag in html is simply <a>, and it is called the anchor element.
Here is how it is used:
1. <a href="https://en.wikipedia.org/wiki/Hyperlink">Click here</a> to go
to the Wikipedia Hyperlink page.
If the link has not been clicked, it will be blue and underlined. Now, click on the
link and you will see that a visited link looks purple and underlined. Apart from
unvisited and visited links, there is also a status called active link. A link
becomes active while the user is clicking on it. During this time, the link will be
red and underlined.
Usage
The <a> tag can surround text or an image.
1. <!-- Text in a hyperlink-->
2. <a href="https://google.com">If you click on me, I will take you to
google.com</a>
3. <!-- Paragraph in a hyperlink-->
4. <a href="https://google.com"><p>If you click on me, I will take you to
google.com</p></a>
5. <!-- Image in a hyperlink-->
6. <a href="https://google.com"><img src="images/google-image.png" a
lt="Image navigating to Google"></a>
You can even use the anchor element to add your email address under the
contacts section of your Web page.
Nevertheless, you should probably avoid using hyperlinks for email addresses:
The only attribute we have seen thus far in this chapter of hyperlinks
is href. href points to the URL that the link should jump to. Though it is
an optional attribute, without it, the <a> tag will not be a hyperlink
The href attribute takes a URL. This URL can be in the form of:
1. <a href="https://google.com"></a>
a link to a file or page within the same Web site also known as relative
URL.
1. <a href="contacts.html"></a>
using its ID. E.g. If you want to link to a div with id='details', the
1. <a href="#details"></a>
protocols such as
1. <a href="mailto:[email protected]"></a>
target specifies the destination where the linked URL in href should be
opened. It can take a variety of different values, but for our purposes we'll
Attribute
Destination Example Result (try this)
value
LINK will open in
In the same view where the same
<a
link resides. If no target is window (Navigate
_self href="https://google.co
specified, this is the default back to the course by
m" target="_self"></a>
behavior. clicking Back button in
browser)
You can learn more about the different device types allowed and the media
rendering values here.
Let's look at another example - you could create a print link to a long content
heavy page that will redirect you to a print version of the same. You want this
print version to be formatted into one page ideal for printing and with
resolution of 250 dpi. Here is how the HTML5 code will look like:
1. <a href="https://en.wikipedia.org/wiki/Media_queries?
output=print"media="print and (resolution:250dpi)">Print wiki page about
media queries</a>
If you do not specify a value for download, it will download the file with name
unchanged. Else it will download the file with file name modified according to
value specified.
... will download the file with the same name - 'hello.txt'.
... will download the file after altering its name to - 'new-name-for-text-file.txt'.
Activities - Hyperlinks
1. Test the anchor element by providing broken or invalid links. How does the
browser respond?
2. Create a simple 'Contact me' page and include the following using hyperlinks
where possible:
In the same page, add navigation at the start for parts of your page like
Introduction, Social Media and Email. Use hyperlinks and the 'id' attribute to
link to each section from nav.
3. Create an HTML page with a link that utilizes the download attribute. Try
your code in Internet Explorer and Google Chrome. What is the difference in
behavior that you see? Why is this happening?
4. Can you think of different scenarios where you would use target values
'_self' and '_blank'?
Try to make good use of semantic elements, images and hash links to get
something like this:
When you're done, or if you get stuck, you can check out the video below to
see what we did.
Welcome to Week 3
Week 3 - Content
3.1 Introduction to Week 3: Get an overview of what CSS (Cascading Style
Sheets) can do for your Web pages.
3.2 CSS basic syntax: Understanding the language of CSS; style tags, links
tags, rules, and comments.
3.3 CSS properties: Here you will be introduced to just a few of the many
properties that make CSS such a powerful tool.
3.4 Lists and selectors: There is a lot more to know about CSS, you are
going to love what it can do for your Web pages.
3.5 Exercises - Week 3: Let's see what you learned in week 3 of the course.
For instance, if you originally wrote your document with all of the paragraphs
indented a certain amount and then later you were decided to change the
indentation then you would have to modify every single paragraph in your
document. It would be nice if there were a central way to set such rules, i.e.
one place that said "I want all my paragraphs to be indented this much", much
like master sheets in a word processor. CSS helps to solve this problem.
An example
Let's see CSS in action. Below we see two identical copies of HTML,
however, styled differently.
1. <p>She looked over the top of her book and whispered <q>I'm
hungry.</q> My heart stopped.<p>
She looked over the top of her book and whispered I'm hungry. My
heart stopped.
Both of these use the exact same HTML. It is the CSS that makes them so
different. So let's get started.
Style and link tags
<style> tag
The best practice when working with CSS is to keep it in
an external file using the <link> tag, however, when
starting, it is simpler to merely place it directly into the
document under edit.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. /* CSS will go in this area */
6. </style>
7. </head>
8. <body></body>
9. </html>
<link> tag
While <style> is convenient, the better practice is to put the CSS into a
separate file. One of the key advantages of using a separate file is that the CSS
styles can easily be re-used between your different .html pages. Many authors
further divide their CSS up into different files (for example one for text styles,
one for layout).
Simply put your CSS into a separate file. This file does not need any HTML
markup (i.e., no <style> tag required). Use the .css file extension and use
a <link> tag to bind it in. The <link> tag must appear in the<head> section.
By convention, css files are kept in a directory named css.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <link rel="stylesheet" href="css/my_styles.css">
5. </head>
6. <body>
7. </body>
8. </html>
Selector
In the above, the selector is p. When a selector appears unprefixed by any
punctuation, then it is assumed to match to an HTML tag. Thus, the p selector
will apply the CSS rule to all <p> tags in the document.
We will cover more selector possibilities in the future.
Declaration
The declaration part of a CSS rule opens and closes with curly braces: { } And
between them go any number of property value pairs.
font-size: 12px;
Best Practices
In the example above, the entire CSS rule is written on one line. This is not
uncommon when the declaration of the CSS rule only has one property. If a
CSS rule has several properties, then it should be written to use one line per
property value pair. For example:
1. p{
2. font-size: 12px;
3. line-height: 15px;
4. color: #223344;
5. }
Comments
CSS can include "comments" as well, by which you, the developer today, can
leave notes and reminders to you, a different developer tomorrow. Or to others
who might read your CSS.
Comments begin with /* and must end with */ and they can span several
lines. But they cannot be nested.
1. p{
2. font-size: 8px; /* client insists small text makes them more 'professional'. */
3. /* I hope his idea of 'professional' includes paying on time. */
4.
5. line-height: 24px; /* see above */
6.
7. /* none of the stuff below is working. I don't know why.
8.
9. margin-top: 5%;
10. margin-bottom:6%;
11. */
12. }
This can also be downloaded directly (zip file) as an Intel XDK project.
The www/index.html is the file we are editing.
1. <!DOCTYPE html>
2.
3. <html>
4. <head>
5. <title>On the Inventor of Gunpowder</title>
6. <style>
7. /* CSS */
8. </style>
9. </head>
10.
11. <body>
12. <h1>On the Inventor of Gunpowder.</h1>
13.
14. <address rel="author">By John Milton</address>
15.
16. <p>Praise in old time the sage Prometheus won,<br>
17. Who stole ethereal radiance from the sun;<br>
18. But greater he, whose bold invention strove<br>
19. To emulate the fiery bolts of Jove.</p>
20.
21. </body>
22. </html>
You could also take another short text (such as a poem) and apply the styles
you like on it.
Below we've gathered a more manageable list of the most useful and common
CSS properties: font-size, line-height, text-align, text-
decoration, font-weight, font-style and font-family.
font-size
font-size can be used to size the text of a tag. The value for the font-
size has two parts: a number and a unit. Some of the most common units
are: px, em, %, vh . For example:
p { font-size: 18px; }
q { font-size: .8em; }
blockquote { font-size: 10vh; }
p { font-size: medium; }
q { font-size: small; }
blockquote { font-size: larger; }
line-height
Whereas font-size may drive the size of the text itself, the line-
height property drives the height of the space it is drawn into. A large line-
height will give the text more spacing. A small line-height will smash the
text lines together.
For example, all of the Middlemarch text below has font-size:16px; But on
the left we see line-height:8px; and on the right, line-height:30px;
Miss Brooke had that kind of beauty which seems to Miss Brooke had that kind of beauty which seems to
be thrown into relief by poor dress. be thrown into relief by poor dress.
line-height supports the same units that font-size does ( px, em, %, vh,
etc)
text-align
Anyone familiar with a text editor will be familiar with this property. Can be
used to align the text left, centeror right. There are additional possible
values like justify and justify-all . Usually defaults to left.
Note that text-align may not work as expected if applied to elements that
are the same width as their text, or whose width is determined by the text
within them (i.e., inline elements). The tags <span>, <a>, <i>, <b>,
<q> and others are considered "inline" because they do not receive their own
new line when used. And text-align is often not useful on these tags.
But it is useful on block level text tags, such as <p>, <li>, <ul>, <ol>, <div>,
and <blockquote>
p { text-align: left; }
blockquote { text-align: right; }
Bear in mind, also, that you should only use text-align when the alignment
really needs to be changed, since it can cause additional work to reverse all the
values when translating into languages that use Arabic, Hebrew, Thaana, etc,
scripts. (The default alignment for those languages is right.) The new values
start and end are currently being implemented in browsers, and those will be a
much better choice than left and right once Internet Exporer supports them.
left center
It was the best of times, it was the worst of times, it It was the best of times, it was the worst of times, it
was the age of wisdom, it was the age of foolishness, was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of it was the epoch of belief, it was the epoch of
incredulity, it was the season of Light, it was the incredulity, it was the season of Light, it was the
season of Darkness, it was the spring of hope, it was season of Darkness, it was the spring of hope, it was
the winter of despair. the winter of despair.
right justify
It was the best of times, it was the worst of times, it It was the best of times, it was the worst of times, it
was the age of wisdom, it was the age of foolishness, was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of it was the epoch of belief, it was the epoch of
incredulity, it was the season of Light, it was the incredulity, it was the season of Light, it was the
season of Darkness, it was the spring of hope, it was season of Darkness, it was the spring of hope, it was
the winter of despair. the winter of despair.
Text-decoration (underline)
How do I underline text? is a common question. In CSS this is done via the text-
decoration property. The values for this are: underline, overline, line-
through, and none; They can combined.
p { text-decoration: underline; }
a { text-decoration: none; } /* hyperlinks are underlined by default, but
that can be removed */
span { text-decoration: overline; }
span { text-decoration: underline overline; } /* apply two with just a space
between the values */
span { text-decoration: underline overline line-through; } /* everything */
Note: there are other properties that can help customize the text decoration,
such as text-decoration-color and text-decoration-skip, but as of this
writing they are not well supported (Firefox only).
font-weight (bold)
Earlier we saw that the <b> and <strong> tags would make text bold-faced.
However, semantically speaking, that is a mere side-effect of the tag. Any tag
can make the text bolder (or less bold) via the font-weight CSS property.
While common values are normal and bold, text can also be made bolder (or
less bold) than its parent with the values bolder and lighter. Lastly,
the font-weight can be set explicitly as a numeric value. The choices
are: 100, 200, 300, 400, 500, 600, 700, 800 and 900. normal maps
to 400 and bold to 700. However, the different numeric choices will only work
for fonts that support a full range of font-weights. Many times the numeric
weights will simply be mapped back to bold or normal.
p { font-weight: bold; }
blockquote { font-weight: 900; }
FONT-STYLE (Italic)
Earlier we saw that the <i> and <em> tags could make text italicized. But, just
as we saw when discussingfont-weight, this can be changed with CSS, and
any tag can make its text italic or oblique with the font-style property. The
choices of values for this property are normal and italic.
font-style: normal; font-style: italic;
Many years later, as he faced the firing squad, Many years later, as he faced the firing squad,
Colonel Aureliano Buendía was to remember that Colonel Aureliano Buendía was to remember that
distant afternoon when his father took him to distant afternoon when his father took him to
discover ice. discover ice.
font-family
Want to set the font for an item on the page? The font-family is the correct
property for the task, but there are caveats:
the various browsers only guarantee a few standard choices: serif, sans-
serif, monospace, cursive, and fantasy.
any other choice must be already installed on the users machine
or you may use a "Web font", but your choices, while plentiful, may not match
the choices you are used to.
your favorite font on your machine is probably encumbered by licensing
limitations and is not available. You can certainly specify it to be used, but if
the end user doesn't have it themselves, they won't see it. And you can't "give"
it to them. Again, "Web fonts" are the alternative here.
The rule above says to first try the font named "Helvetica". If it isn't available,
try "Verdana", failing that "Arial", and lastly fall back to the built in sans-
serif browser font.
p{
margin-left: 10px;
margin-right: 10px;
margin-top: 10px;
margin-bottom: 10px;
}
Color
The color property can be used to set the text color of an element. There are
several possible formats for the value.
Named colors
p { color: blue; }
b { color: transparent; } /* transparent */
i { color: lightgrey; }
There are scores of different names. The most common English names for
colors are all supported, plus many others.
One of the more interesting is transparent, which will make the text invisible.
However, if you want to make an HTML element invisible, then
the display:none; or visibility:hidden; rules are preferred. They are discussed
in a future section.
rgb/rgba
p { color: rgb(10, 200, 255); }
p { color: rgb(0, 0, 0); } /* 0,0,0 is black */
p { color: rgb(255, 255, 255); } /* 255,255,255 is white */
b { color: rgba(10, 200, 255, 0.5); } /* semi-transparent */
Generally, any color on a computer is exactly specified by mixing three
components together: red, green, and blue. The amount of each component
falls within a range between 0 and 255. So the rgb() function can be used to
specify a color.
rgb( red, green, blue);
parenthesis required, commas between each component.
Similary, the rgba() function can be used for semi-transparent colors. The
fourth value is for the "alpha channel" (thus the "a" in "rgba") and means the
opacity. It is a number between 0 and 1 (for example, 0.5 ).
Hex code
p { color: #3A2BFF; }
Quicker than the lengthy rgb() function is simply providing a hex code. This
always starts with the pound sign (#) and is followed by three pairs of hex
number, ranging 00 to FF. Constructing rgb triplets is hard enough, and
deciphering and generating hex codes is even harder. However, almost every
editor and color picker will at least show you red, green, blue values and many
have hex code displays as well.
px
'px' is short for 'pixel', which is a single dot on the screen. So text with font-
size:20px is 20 pixels tall on-screen. In actuality, due to browser zooming,
retina displays, or other factors, this may or may not match to 20 physical on-
screen pixels.
All the text sizes above are relative to the pages base size. You'll see radically
different results on the rest of the page from either of these rules applied to
the body, but relative to one another they'll remain sized correctly.
rem
'rem' is much like 'em', except that 'em' sizes an element relative to its parent,
and 'rem' always derives its size relative to the root. In an HTML document
with lots of nested elements, 'rem' will generally prove to be more reliable than
'em'. 'rem' is supported in all modern day browsers, including mobile, but not
older ones.
Using the CSS rules from the em section immediately above, nested list items
(<li>birds<ul><li>hawk</li></ul></li>)would get increasingly
smaller. And if 'rem' units were used, they would be the same size.
%
Whereas em is a measure relative to the parents text size, the percentage unit
(%) is relative to the parent dimension. This is a useful unit for both horizontal
and vertical dimensions, though often more useful in the horizontal.
p {
margin-left: 10%;
margin-right: 10%; /* 10% of parent width will be spent on the two side
margins */
}
Initially, the percentage unit may seem very handy (and it is), and many
developers fall in love with it. But the love affair is usually short lived. One of
the limitations of this rule is that for it to work correctly, the parent must have
an explicit width or height set. This limitation is particularly noticeable in the
vertical dimension. If the parent element doesn't have an explicit height set
then child percentages may be percentages of 0.
vh / vw
'vh' stands for viewport height, and 'vw' for viewport width. The vh and vw
units work much like the percentage ( % ) unit. But instead of percentage of
the parent, it is percentage of the screen (aka viewport). Obviously, vh is for
vertical dimensions, and vw for horizontal dimensions.
vh and vw do not suffer the parent limitation that the % unit does. Most
modern browsers support these units, but there are some exceptions on older
mobile browsers.
p {
margin-left: 10vw;
margin-right: 10vw; /* 10% of screen width will be spent on the two side
margins */
}
External Resources
The list of CSS units above is not exhaustive. There are various tutorials and
explanations about CSS units on the internet. Here are a few that you might
find helpful.
This CSS Tricks article from March 2016: "Use for Global Sizing; Use for Local
Sizing"
New CSS3 Units: Root EM and Viewport Units
From the W3C specification: Viewport-percentage lengths
With great power comes great
responsibility
The CSS rules with which we've started are
fun and easily understandable. They are
mostly concerned with typography. Later
we will see how to use CSS to include
decorative image, look at other decorative
properties, and take up the topic of layout.
Guidelines
For accessible typography, there are really just a few things to avoid:
1.do not make text too small
2.do not make lines of text too tight
3.do not use foreground and background colors that are too close to one
another, in other words, ensure there is good color contrast
4.do not irregularly space text or make it jump around
Look at those four guidelines. Can you match each guideline to one or more
CSS property from earlier? Take a moment and think about it. We'll touch on
specific rules below.
Properties
Font-size
Misuse of font-size might make text too small. So be wary of that.
Furthermore, in the past the gold standard practice was to use em units instead
of px. This is no longer as true as it was, but the practice of
using em or rem units is definitely be encouraged and it should be your default
unit when working with text.
Line-height
An overly small line-height will cause lines to become cramped and difficult
to read. Even the largest text can be rendered unreadable by a too small line-
height. Generally, your line-height should always be at least one and a half
times the font-size, (ie, line-height should be greater than 1.5em ).
Color
Color contrast can be easily undone by misuse of the color property. The
exact rules for contrast are rather advanced. For example, "wide stroke" text is
allowed to have less contrast than narrow stroke text. But, regardless of rules,
the overall concept is easy to understand: keep your text high contrast to the
background. There are further color guideline concerning certain combinations
(like bright blue text on a bright red background), but the rule of thumb is that
if the text is at all hard for you to read, then just assume it is unreadable to
someone with a visual disability. If you are interested, there are tools that
can help such as Tanaguru Contrast-Finder or Juicy Studio Luminosity Colour
Contrast Ratio Analyser.
Text-align
Any long passage of text should have its alignment match its reading order.
Which means, if the language is English, which is read left to right, then any
long passage of text should be aligned left. Right aligned or center aligned
text can be very hard for dyslexics. Likewise, text-align:justify should be
avoided as well. It will put irregular gaps in the text making it very difficult.
Obviously, a header or perhaps a menu might be exempt, because they are not
typically long passages of text. So this guideline doesn't mean an end to good
page layout and typography.
Summary
So now we've seen how typography can affect the accessibility and
approachability of your page. It is not so very difficult. Common sense and
awareness are good companions and will serve you well.
If you are interested in accessibility, there is much more to learn, these simple
guidelines merely scratch the surface.
Activity - Units
With the HTML below, please size the text using different units:
Use px units to set the root size of the text for the document.
Use rem units to size the h1 and li tags.
Change the text size of the root CSS rule. You should observe all the text of
the document adjusting appropriately.
Change the h1 so that it uses px units. As the root CSS rule is changed,
the h1 will no longer adjust with the rest of
the document.
1. <h1>Books</h1>
2. <ol>
3. <li>A la Recherche de Temps Perdu</li>
4. <li>Middlemarch</li>
5. <li>Ulysses</li>
6. <li>Don Quixote</li>
7. <li>Moby Dick</li>
8. <li>Hamlet</li>
9. <li>War and Peace</li>
10. <li>The Odyssey</li>
11. <li>The Great Gatsby</li>
12. <li>The Divine Comedy</li>
13. <li>Madame Bovary</li>
14. <li>The Brothers Karamazov</li>
15. <li>One Hundred Years of Solitude</li>
16. <li>The Iliad</li>
17. <li>Lolita</li>
18. <li>Anna Karenina</li>
19. <li>Crime and Punishment</li>
20. <li>The Sound and the Fury</li>
21. <li>Wuthering Heights</li>
22. <li>Le Rouge et le Noir</li>
23. </ol>
NOTE: This activity is best conducted in the XDK (or in CodePen), not in the
discussion forum below. The discussion forum includes its own stylesheet which
may override the styles you want to experiment with.
Styling lists
The list markup tags (<ul>, <ol> and <li>) are some
of the most frequently used specific purpose tags in
HTML. There are a few CSS style properties that are
available for lists.
list-style-type
list-style-type governs the little list marker that is
usually positioned to the left of any list item. For un-
ordered lists (<ul>) There are several popular values: disc, circle, square,
and none.
li { list-style-type: disc; }
</ul>
For ordered lists (<ol>) you can choose different ways of having the numbers
shown: decimal, decimal-leading-zero, lower-roman, upper-roman, lower-
alpha, upper-alpha, as well as several of the worlds
languages: armenian, georgian, simp-chinese-formal, and many others.
list-style-position
Besides choosing the type of marker applied to each list item, you may also
want to govern how closely it is positioned to the list itself. The list-style-
position property handles that. The two values are inside and outside.
They govern whether the markers are positioned inside the box of the list, or
outside. This is most evident if a border or background or similar is applied to
the list. Below, we have put a blue border on the list.
outsi insi
de de
1. egg
1. eggs s
2. milk 2. mil
k
3. brea
d 3. brea
d
list-style-image
The little markers on a list can also be customized to be an image of your
choosing. This will require you to have a small image in a Web compatible
format (PNG or JPEG recommended) and to know the path from the place
where the CSS is being defined to the image. Image pathnames were covered
in Week 2, and we'll be discussing them again in the background-image
section.
li { list-style-image: url("my_triangle.png"); }
list-style-
image
eggs
milk
bread
Note that the browser will do little more than draw the image. There is no
guarantee to scale the image or assist with spacing or alignment. Many users
find list-style-image to be frustrating and instead use the background-
image CSS property which has more options. There is a section dedicated to
the background-image property.
Selectors
Earlier, we learned that a CSS rule is made up of two parts: the selector and
the declaration. We've seen quite a few different declarations, but the only
selector we've learned is the tag selector. There are other choices, and they
can be composed together in interesting and useful ways. So let's learn some
more CSS selectors.
Tag selector
We've already seen this one. A CSS selector that consists solely of a single
tag (without punctuation or spacing) will be applied to any matching tag on the
page.
li { list-style-type: circle; }
id selector
You may remember the id attribute (short for "identifier"). This attribute can
be applied to an HTML tag to uniquely identify the element. Recall that the
value for any given id attribute can only appear once in a document. No two
tags are allowed to have the same id. You may also recall that the id cannot
contain spaces, nor most punctuation, nor begin with numbers.
In the HTML below, there are two paragraph tags. So to style the individually
we can apply unique id attributes to the paragraphs.
( id="p18" and id="p19" ) In the CSS, we will use the id selector. The id
selector is simply a hash sign (#) followed directly by the id.
CSS:
HTML:
<p id="p18">He is Ulysses, a man of great craft, son of Laertes. He was born
in rugged Ithaca, and excels in all manner of stratagems and subtle
cunning.</p>
<p id="p19">Madam, you have spoken truly.</p>
Result
He is Ulysses, a man of great craft, son of Laertes. He was born in rugged Ithaca, and
excels in all manner of stratagems and subtle cunning.
Class selector
The class attribute is similar to the id. However, whereas the id must be
unique and singular, the values of the class attribute can be shared by
multiple tags. And, multiple classes can be assigned to a tag by simply
separating them with spaces.
HTML
<ul>
<li class="bird flying">eagle</li>
<li class="bird">ostrich</li>
<li class="insect">ant</li>
<li class="insect flying">moth</li>
</ul>
The class selector is simply a period (.) followed by the class name itself.
CSS
.bird { color: blue; }
.insect { color: green; }
.flying { text-decoration: underline; }
Result
eagl
e
ostri
ch
ant
moth
Combining selectors
Being able to define a CSS selector in terms of a tag, class or id is very
powerful. But it's not practical to place classes on every tag in your document,
much less to put unique ids throughout. It's also inconvenient to constantly
repeat CSS rules. But by combining composing selectors all that can be
avoided.
separate joined
blockquote { blockquote,
color: red; q,
font-style: itali .speech {
c; color: red;
} font-style: italic;
q {
color: red;
font-style: itali
c;
}
.speech {
}
color: red;
font-style: itali
c;
}
The joined version on the right is much easier to read and maintain.
If the "speech" items need to also be bold, that can simply be added by an
additional rule:
blockquote,
q,
.speech {
color: red;
font-style: italic;
}
.speech { font-weight: bold; }
Specialized selectors
If two selectors of different types (like tag and class) appear next to each other
with no spacing separating them, then they form a specialized selector. To
match a candidate must match both rules. If a tag selector is used, it must
appear first.
This is most useful with class and tag selectors, like so:
<ul>
<li class="bird
flying">parrot</li>
parrot
<li class="bird">ostrich</li> .insect.flying {
ostric
h
<li class="insect">ant</li> text-decoration:
underline;
ant
<li class="insect
flying">wasp</li> font-weight: bold;
wasp
<li class="insect }
flying">moth</li> moth
Descendant selectors
In the following HTML we see some paragraph that have some links
(<a>) inside. The link tags are inside the paragraphs, but not necessarily direct
children.
1. <section id="intro">Welcome
to <a href="#palaceland">PalaceLand</a>, world renown <q>Land of
endless palaces and <a href="#delight">delights</a></q>. As you make
your way about, remember the words of our founder <blockquote>Shouldn't
we have <a href="#chairs">chairs</a>? Never made much sense wandering
room a room looking for a place to sit a spell. Folk that don't sit are not likely
all right in the <a href="#head">head</a></blockquote></section>
2. <section id="guideline">There are guidelines to follow while
in <ahref="#palaceland">PalaceLand</a>. They are outlined on the back of
your <q>Daring Footman <a href="#trademark">(tm)</a></q> card. But
the spirit of the guidelines are best summed up by our
founder <blockquote>Don't just <ahref="#standthere">stand
there</a> with your mouth hanging open waiting for a pair of nesting
birds.</blockquote> (and no <a href="#camera_policy">flash
photography</a> please.)</section>
What if we wanted all the links in the introductory section to be red, but all the
link in the guideline section to be green? That is what descendant selectors
are for. Here is an example for the problem we are facing:
So, in the first rule, we see that the selector will match to any <a> tag that is a
descendant of #intro. The <a>tag can appear directly within #intro, or be
buried within its children. Here is the result:
Welcome to PalaceLand, world renown Land of endless palaces and delights. As you make
your way about, remember the words of our founder
Shouldn't we have chairs? Never made much sense wandering room a room
looking for a place to sit a spell. Folk that don't sit are not likely all right in
the head
There are guidelines to follow while in PalaceLand. They are outlined on the back of your Daring
Footman (tm) card. But the spirit of the guidelines are best summed up by our founder
Don't just stand there with your mouth hanging open waiting for a pair of
nesting birds.
But what if we want the links in the founder blockquote in the intro section to
be bold? Again, a descendant selector will work. We add this:
body > * { margin-left: 10px; } /* all the _direct_ children of the body
receive the margin */
p * { text-decoration: underline; } /* the text of the paragraph will be
normal, but any children anywhere inside it will be underlined */
Cascading:
inheritance
and
precedence
Inheritance
Now that we've covered several
ways of defining CSS selectors
we need to understand what
happens when multiple selectors
resolve to the same element,
and how an element can get
inherit rules from its parent.
Most CSS rules once applied to an element are also applied to all the children
of that element, and to their children, and theirs ad infinitum. There are
exceptions, notably the layout properties (margin, padding, position, width,
etc) and the decorative properties (border, backgrounds etc) do not cascade.
This cascading of a CSS property from parent to child is also called
"inheritance".
Generally, inheritance is a good thing. Do you want the whole page to use your
corporate approved Web-font? body { font-family: "Soulless", serif; } is all
you need. There is no need to apply the same font-family property to each
and every tag used within the page. Thanks Cascading!
Inheritance can be explicitly leveraged. Many CSS properties accept the value
of inherit, which means to inherit the value from the parent. By smartly
leveraging inherit you can make reduce repetition in your CSS rules and
make your project easier to maintain.
HTML
<q>With this structure, we can see how some CSS <span>rules</span> are
<span>applied across a <q>variety</q></span> of scopes.</q>
</p>
Discussion
To the right we add another CSS rule, this one instructing that the padding for spans and q element
Precedence
It is possible, and easy, to have several different CSS rules all applying to the
same element. This is often advantageous because most CSS properties
are orthogonal to one another, meaning they do not interfere with each other.
This gives us freedom to organize the CSS properties in rules in ways that
make sense to us as developers, knowing that they can compose nicely. For
example, a bit of text can be made italic by one rule, bold by another, and
underlined by a third. We do not have to put all those properties into one place
if that is not convenient for us.
However, what happens when there are different rules competing to set
different values for the same property? This is where CSS precedence comes
into play. When rendering CSS the browser has some guidelines it follows for
resolving conflicting rules. Here is rough summation, in order:
1 - Most Specific Rule
A more specific rule takes precedence over a less specific rule. A rule that
more tightly matches a particular element than a general rule will be applied.
span { color: blue; }
ul li span { color: red; }
In the example above, both rules are attempting to set a span color for a span
inside a list item. However, the second rule will "win" when there is a conflict
(like color in this case).
2 - #id selector is the most specific.
Rules with an id selector (e.g. #someid ) are considered more specific than
rules without.
3- .class selector is more specific than a tag selector
Rules employing a class selector (e.g. .someclass ) are considered more
specific than rules without (but not as specific as an #id selector, which trumps
everything)
4- Rules that come later override those that come earlier.
This guideline is for two CSS rulesets with the same selector. Where there are
conflicts, the rules from the later one apply.
.hortense { color: red; text-decoration: underline; }
.hortense { color: blue; }
In the example above, an element with the .hortense class will be underlined
and its color will be blue, because that rule came later than when it was set
red.
No Fear
These guidelines seem fairly straightforward, but situations can quickly get
rather knotty. For example, what color should we expect in this situation?
HTML CSS
What if the order of the CSS rules were reversed? Would it make a difference?
If this problem seems difficult to figure out, don't worry about it. In the next
section we will be looking at Chrome Developer Tools and you'll see how you
can use the tools in the browser itself to inspect your elements and see exactly
what CSS rules and properties are being inherited, applied and their
precedence.
!important
p { color: orange !important; }
Because multiple CSS selectors can resolve to the same element, and because
the rules that govern precedence are complex, you may from time to time
encounter a situation where you need to apply a particular CSS property and
you want it to take precedence over all others, no matter what. !
important will do that.
The exclamation point is required, and the whole symbol ( !important ) goes
after the value and before the semi-colon ( ; ).
This may seem like an attractive option, but using it is not recommended. Once
you start to use it then you'll eventually run into a conflict with the various
rules that are using !important, and from that conflict there is no escape. If
you are having problems with precedence the best advice is to fix them
directly, rather than using !important.
Activity - Lists
The HTML that follows is for a simple list. Insert it into a properly formed HTML
file and format it. Try to ensure the following are done:
space the list items at least 20 pixels from the left edge of the page
space the list items at least 10 pixels from each other
center the header
keep the list at least 50 pixels from the header
the book titles in the list should not be displayed in a serif font
the header should use a different font than the list
the text of header should be dark red
break the CSS rules into two different .css files. One file should contain any
spacing rules, the other any rules governing font faces or coloring. Bind both
into your HTML document
instead of numbers, have the list items indexed by the alphabet.
change the <ol> tag to <ul> (and the closing </ol> to </ul>) and style the list
items to have square bullet points.
download this simple triangle shape and style the list items to use it.
You can directly download (zip file) this as an Intel® XDK project. The file to
edit is www/index.html
1. <h1>Books</h1>
2. <ol>
3. <li>A la Recherche de Temps Perdu</li>
4. <li>Middlemarch</li>
5. <li>Ulysses</li>
6. <li>Don Quixote</li>
7. <li>Moby Dick</li>
8. <li>Hamlet</li>
9. <li>War and Peace</li>
10. <li>The Odyssey</li>
11. <li>The Great Gatsby</li>
12. <li>The Divine Comedy</li>
13. <li>Madame Bovary</li>
14. <li>The Brothers Karamazov</li>
15. <li>One Hundred Years of Solitude</li>
16. <li>The Iliad</li>
17. <li>Lolita</li>
18. <li>Anna Karenina</li>
19. <li>Crime and Punishment</li>
20. <li>The Sound and the Fury</li>
21. <li>Wuthering Heights</li>
22. <li>Le Rouge et le Noir</li>
23. </ol>
if possible.
Can you achieve the same styling without adding any new tags (ie, without
You can directly download this project as an Intel® XDK project. The file
to edit is www/index.html
NOTE: Depending upon your browser, the bullet points on your list
may be the same color as the text or not. (In the screenshot
Week 4 - Content
4.1 Introduction: This week you will begin learning how to fix your Web page
when it's not doing what you hoped it would do.
4.2 Tools: Learn about tools and accessibility and how they relate to
debugging.
4.3 The Box Model: Understanding the CSS Box Model and how to control the
spacing of elements on the page.
4.5 Give Your Mind a Workout: Lets see what you have learned about
debugging your code.
Tools
One tool that you should, by now, be very familiar with is the editor.
While traditional text editors allowed you to enter and edit text, modern
editors can actually help you detect and avoid errors, visualize your
program more clearly, and even stick in bits of text for you if it thinks it
Some of the most ubiquitous tools are in the browser itself, which is handy
because everyone seems to have one. You might have even seen this
yourself if you've ever tried the "Show Source" button, but perhaps the
most important tool that we have yet to explore is the debugger activated
While it's important that your page looks and acts the way you intend,
designing your page so with various disabilities in mind. For someone with
impaired vision, you'd want to make sure that your page is zoomable, or
ramps are a benefit for many users (ask anyone who's had to drag a stroller
up the stairs), making your Web site accessible can be a benefit for many
users.
your page, see how it looks to a screenreader and even figure out how well
your background a foreground colors interact. For a good list of such
Debugging
being taken through the code, and whether the program crashes, usually
procedure in order described by the program. Just think of how you might
direct a small child, "Go into the bathroom, stand in front of the sink, pick
your mouth, but don't swallow the toothpaste etc, etc." It can be a bit
tedious, but then you've got a better chance that the end result will be
accomplished.
HTML and CSS are not procedural languages, they are "Declarative". You
declare what you want, and the computer makes it happen. You say "this is
your mark, get set GO!". You don't proscribe exactly how it's done, just
what you want the result to be. Now you're dealing with something more
like a teenager - "I want to see this room sparkle! And I should be able to
bounce quarters on that bed!". Less tedious, just sometimes it's a bit
In either case, you might need some help. With a small child, you might
correct any unexpected variations that might occur. For teenagers you can
usually listen at some distance and figure out what's happening (or not
happening).
Since we are focusing on HTML and CSS, let's consider what sort of info
may be helpful. There are several things that can go wrong with our
programs. Some text might be missing. Some things will be in the wrong
place. Some things might be too close together, while others are too far
apart. You thought you had everything right, but it doesn't look quite right.
How to figure out where the problem is? That's where Development tools
come in.
Every browser is a bit different, but most of them have ways to examine
see what's going on with particular elements of the HTML page, at least or
we'll cover uses the "Chrome Developers Tools" which is the same tool you
browsers are likely to have similar capabilities, but the user interface may
be a bit different. Feel free to use whichever tools you prefer, but the
XDK.
To start debugging, switch to the "Emulator" tab, and you should see these
controls in the upper left part of the window:
Under the little folder symbol and the word "PROJECTS" there are 4 buttons.
The first one, with the two curved arrows in a circle is the "Reload" button, you
can hit that when you want to start over, for example if you've made some
changes and you want to restart with the initial conditions. The third button is
to set some emulator preferences, and the 4th will clear the emulator, so it
won't display your code until you "Reload".
The second button is the one we'll be talking about the most, that's the
"Debugger" button which will open and close the debugger:
Displaying Elements
When you open the Debugger by clicking on the Debug button, a second
window should pop up containing CDT (Developer Tools, including the
debugger). This window will appear above the Intel XDK window, so you may
want to rearrange the two windows so that neither is blocking the other. Once
you set up the size and position of the debugger window, the emulator should
remember and bring it up the same way the next time you use it.
Identifying elements
Remember that Elements are the intangible parts of your Web page, which are
described by the text in tags and are rendered on the screen of whatever
device you're looking at your Web page with. The two things (the text code and
the pixels on the screen) correspond to each other, but it's not always obvious
which bit of the screen corresponds to which bit of text.
There are two opposite directions in which you might need to figure out in
these two different things that both correspond to an element. You might have
some HTML5 code that you've written and want to find out where on the Web
page that code shows up. The other direction can be needed as well, i.e. given
a particular part of the page, what part of your code produced it?
This highlighting not only tells us the correspondence between the two (source
code and rendered page), it also shows us the extent of the rendered element.
We can see how big it is, whether it goes all the way across the screen or just
part of it and so on. In addition to the highlighting there is a small rectangle
with an arrow with the dimensions in pixels of the element, giving us exact
information about the size of the element.
You probably notice that there is another highlighted element on the left, that
is the currently active element, made active by clicking on it. While it's not
highlighted in the display window on the right, it's importance is that changes
in the "style" panel will affect that element.
It is also possible to go the other direction, i.e. click on a point on the screen
and it will highlight the code in the source that corresponds to that element.
This is helpful when you want to figure out where something came from and
what might be affecting it's styling (size, color, font, any number of other
characteristics). To do that in the Intel® XDK debugger you need to use the
"Magnifying Glass" button in the upper left corner of the debugger window. In
other browsers, this essentially corresponds to the "Inspect" function.
When you click on the little magnifying glass, it should turn gray (lighter than
normal) then when you go to the emulated window. You may need to click on
it once to make it the active window on your machine, then when you hover
over any given pixel it will highlight the lowest level (smallest) element. You
will stay in this "Magnifying Glass" mode until you click on a pixel, or if you go
back and click on the magnifying glass symbol again. When you click on a
pixel, it will select the code for that element back in the debugger, opening up
any parents if necessary.
It's possible to change things a few different ways. If you double click on an
element in your HTML5 source code, you can change the source code. For
example you could click on an attribute to modify it or it's value, or you can
change the type of the tag or even the contents of an element.
You can use this same approach to add a "style" attribute to a particular
element, which should override any other settings, there is also an easier way
to do that. In the panel just to the right of the elements panel is the another
panel with tabs including "Styles" and "Computed" and a few others. Most of
the time we'll want the "Styles" tab activated. Once you do that, you can
modify CSS properties of the current element by adding them to the
"element.style" box at the top of the "Styles" panel.
Just click in between the two curly braces on the "element.style" rule at the top
of the Styles panel. After clicking you should see a little text entry box with
which you can type property value pairs that will then effect the currently
active element.
It's important to know that any changes you make in the debugger will have no
effect on the original Web page. They only affect that particular instance of
that page during that debugging session. If you navigate to another page and
come back, you'll need to make the same changes again if you want to get
back to where you were. It's not that easy to break the Web!
Activity - Debugger
Using your favorite browser, navigate to Wikipedia.org. Using the debugger,
change the title and header of the page to "My Wikipedia" and change the
background to light green.
In another browser window, open up Wikipedia.org. Does it look like the one
you've modified? Why or why not? Did you just break Wikipedia for the rest of
the world?
Perhaps the best way to understand is with a picture. All elements in an html
document end up being treated as rectangles somewhere in the window.
The content of each rectangle corresponds to the innermost rectangle in the
image below. Just outside the content is the padding. This is kind of like an
internal margin, meaning that it separates the contents from the border. The
border essentially traces the sides of the padding rectangle.
It's important to note that the border goes around the content and the padding.
There are sometimes visible things associated with an element that are not
technically part of the content of the element. One such example is the list
item:
The box does not include the bullets because it is outside of the content.
Sometimes when you see that it might be a bit confusing, especially because it
also affects padding (which is inside the border).
padding-left: 1rem;
Now the bullet is inside the border, and padding affects the bullet as well as the
text.
The border property has a lot more options than the padding or margin.
Imagine using a pen to draw the edges of a rectangle. You can choose how
thick the pen is, and whether you draw a solid or dotted line. You can even
choose how you go around the corners, whether it's a sharp turn or a more
gradual circular shape. All of these characteristics can be controlled by CSS
properties, like border-width, border-style and border-radius.
While all of these border properties have default values, there are three that
you'll see most often when specifying a border: border-width (the size of your
imaginary pen), border-style (dashed, dotted, solid, etc.) and border-
color (the color of your pen). In fact these are so commonly specified that
there is a shorthand syntax to set all three in one line:
There are many other shortcuts to learn, but this one is fairly common. To
draw a border you need to know the width, style and color. There are defaults
for these values, so you technically don't need to specify all of them, but it is
the minimal info needed and is quite common.
The margin, as we learned last week, specifies the position of the
element relative to whatever is adjacent to it, either to the right or left, or top
or bottom. The margin is always transparent, and each side can be set
individually. The unique thing about the margin is that the values for any of
the sides can be negative, even if that means that it overlaps with another
element on the page. This can be useful when you want to control where an
element is placed on a page. In the following pictures, the black rectangles
encompass the content:
On the left we see three blocks with no margins between them. On the right
are the same 3 blocks, but now block 2 has a positive margin-left, creating
space between blocks 1 and 2. Block 3 has a negative margin-left, causing its
left side to overlap with block 2.
Here blocks 1, 2 and 3 all have borders with different widths, but the margins
are zero. There is no overlap, the borders are up against each other regardless
of their width. The contents have different positions, influenced by the width of
the border. If we were to make the borders invisible (fully transparent), the
positioning of the contents would be the same.
Inside the border is the padding. This controls the amount of space between
the elements content and the border box (whether it's visible or not). If you
have no padding, then the contents of the element (maybe text or image)
would be right up against the border, which could be awkward if you have a
visible border.
Like the margin and the border, all four sides can be independently set. The
background of the padded area matches the background of element, so the
effective visible size of the element includes the padding.
Here we've got a thin border directly around the content to delineate where the
content ends and the padding begins. Again, the contents are affected by the
width of the padding, but now the background of the padding is the same as
the background of the content. This makes it look more like the contents have
been expanded. If we add a thin border to these, we see that the padding is
reflected by empty space between the contents and the border:
All of these can have a width of 0, which is equivalent to not having them,
thus 'margin: 0;' is the same as 'margin: none;'. Each can be controlled
individually with relative or absolute lengths. While the padding and borders
require non-negative widths, margins can be either positive or negative.
Activity - Birds
Download and import this Intel® XDK project - birds.zip. After you unzip it, you
can either open it in Intel XDK by going to the project tab and selecting "Open
an Intel XDK project" at the bottom left, or navigate to the www directory and
open the index.html file with your favorite editor and browser. You should see
a list of various sea birds common to the San Francisco Bay Area. Let's see
what we can do to improve the look of this page.
First, the pictures and names are a little cramped, it would be good to have
some space there. It would also be helpful to have some vertical space
between the pictures. Finally, it would look nicer with some sort of frame
around the pictures. We'll start by examining the box model measurements of
the images in the debugger.
First, we'll add some space between the names and pictures of each bird. For
that we'll want to use a margin, particularly on the left:
margin-top: 3rem;
The placement of the words at the very bottom of each picture is a bit awkward
as well. We can improve that by moving each image down using a negative
bottom margin:
margin-bottom: -1rem;
Next, we can add a frame around it. Using a border, provide a simple frame
around each picture:
padding: 5px;
Though not perfect, it looks a bit better now, with more space and a frame
around each picture:
Activity - Rectangles
Create a simple Web page with some rectangles distinguished by their
background color so you can see them. You can create the rectangles using
spans and/or divs, and explicitly setting the width and height. They need to
have some content or else they'll be of size 0, so you need to put some text or
at least an inside, but then you should be able to adjust the height and
width using CSS.
In the debugger, try modifying the padding, border and margin settings using
the arrow keys to modify numerical values so you can see how the changing
number affects the element. Be sure to try border-radius and see if you can
create a circle or oval. Be sure to try out some other border attributes like
style and color. If you're feeling brave, you could even try border-gradient.
Nevertheless, that can cause problems when you have different rules that
could apply to the same element. Consider the following example:
Looking at the style rules we see there are three different possibilities for the
size and color of an <h1>element. In this case the application of the rules
seems pretty intuitive. The outermost heading is neither in a Article or a
Section, so it is blue and largest of the three. The one that's in the Article, but
not in the section is black and of medium size.
Finally, the heading in the section is the smallest and shows up as grey.
Your intuition may be thinking along these lines - "section h1" is more specific
than "article h1" or "h1", and therefore it takes precedence resulting in smaller
gray text. However, when you re-arrange the rules you get a different result:
There is a sequence of the panels under "Style" that helps understand just
where a particular CSS rule is coming from. Starting at the top, we have rules
that apply specifically to the currently active element. In fact changes in this
top panel are mirrored as settings in the style attribute of the element:
Under that there are more panels which show where CSS properties for other
the elements come from. Under the top panel, which corresponds to inline
style settings, we find properties for this element that came from the rules with
the selector "article h1". This may seem odd at first because the h1 element
that we're examining is inside a section, so you'd think that the "section h1"
selector would take precedence.
If we keep going down, we find the overridden rule that applies to all h1
elements, and then there are the two grayed-out section with the label "user
agent stylesheet". These are basically the defaults, the values that the
browser will use if nothing else is specified. Any rule you provide should
override the corresponding rule in the user agent stylesheet.
Back to our quandary, why does "article h1" take precedence over "section
h1"? Let's take a look at the first version we tried, before rearranging, which
did what we wanted:
Here we see just the opposite of what we saw before, now "section h1" takes
precedence over "article h1". What's going on?
Our intuition in this case is deceiving us. We think of section as being more
specific than article, but that's just because we've organized it that way. In
fact, we could decide that a section consists of multiple articles, then we'd
want the opposite behavior.
We could fix it by just making sure things are in the right order (which is
important) but a more robust solution might be to make use of the fact that the
way we're using <section> in fact is more specific than <article>. We can
make this explicit by changing the selector to "article section h1", so that now
the smaller, lighter color will be used only on a section that is inside a article,
which is really what we want:
Cloud images
We're working on a Web page about clouds (download Intel® XDK
project here), and we have some beautiful pictures we'd like to use: one for the
top of the page, and others as examples of different types of clouds.
We include the pictures but the result is unwieldy:
I zoomed out so you could see what it looks like. However, when you see the
pictures, the text is so small it's unreadable. The other option is to leave it un-
zoomed, scroll back and forth to see all the parts of the pictures. Clearly we
have a solution for this. We can just specify the width of <img> elements in
our custom.css file. We can use the debugger to try different sizes, modifying
it in the "Styles" panel and we decide on this:
1. img {
2. width: 10rem;
3. }
So far so good, but we want our top image to be a bit bigger without changing
the other images. Recall that an <img> tag includes a width attribute, so we
can special case this image accordingly in the HTML code:
We look at our page again, and it hasn't changed! Time to try the debugger
again.
1. img {
2. width: 25rem;
3. }
4. li img {
5. width: 10rem;
6. }
Shrinking text
For this section you can either download this essay outline, or type (or
copy/paste) in the code from the examples below. The main content is an
outline for an essay and it should look something like this:
1. <section>
2. <h1>Essay Outline</h1>
3. <ol>
4. <li>Introduction
5. <ol>
6. <li>Introduce Subject
7. <ul>
8. <li>What is it?</li>
9. <li>Why is it important?</li>
10. </ul>
11. </li>
12. <li>Propose Thesis</li>
13. <li>Outline</li>
14. </ol>
15. </li>
16. </ol>
17. </section>
As with the cloud pictures, we want the listed items a bit smaller than the
regular text, so we add this styling:
1. section {
2. font-size: 24px;
3. }
4. section h1 {
5. font-size: 28px;
6. }
7. li {
8. font-size: 0.5em;
9. }
Now we look at our resulting rendered page, and get this surprise:
The outermost level is fine, the next level is almost readable but the innermost
level is ridiculously small. Back to the debugger to see what's wrong.
Computed tab
Looking into the style settings in the debugger, at first glance we don't see
anything unusual. The font-size is .5em as expected. One odd thing is that
below the user agent stylesheet panels is the over-ridden font-size setting
identical to the current one, i.e. .5em on <li> elements.
The styles panel doesn't tell us a lot about the actualy font-size in absolute
terms. To determine that we can use the "Computed tab".
The 'computed' tab contains the values of all the CSS properties that apply to
the current element. There are a lot of them, and they're listed in alphabetical
order. Since the computer considers the character '-' as coming before 'a' in
the alphabet, the first thing you'll see is a long list of properties starting with '-
webkit'. We're going to scroll down past those to "font-size" which reveals this:
This tells us that the font-size on the innermost list item is only 3px. No
wonder it's unreadable.
When we click on the triangle we can expand the details on font-size, which
makes a little more clear what's going on. We see that the font-size on the
body is 24px, but there are several repetitions of the li .5em.
If we look at the next outer list item, we see that the font-size is 6px, and the
one outside of that is 12px. This doubling makes it clear what's happening.
Each nested <li> element has a font-size 1/2 the size of its parent, because
the em unit is relative measurement, depending on the current font-size.
Now that we know what's happening, we can fix it in a few different ways. We
could use an absolute unit like px or pt, but a better solution would be rem.
This would make the size relative to the html font-size (the default font-
size for the page), not to it's surroundings.
If you'd like to see what we did for Week 3, you can find it here.
When you're done, or if you get stuck, try watching the video below to see
what we did.
Good luck!
Welcome to Week 5
Week 5 - Content
5.1 Introduction: This week, you will be combining HTML and CSS to create
more complex pages.
5.2 Tables: Tables can be a great way of organizing your content — learn
when to use tables, and when to avoid them.
5.3 Multimedia: Learn the best methods for including audio and video in your
page.
5.4 Embedding content: Learn about iframes and some advanced image tag
attributes, ismap and usemap. Note: This section is optional material included
for the curious. It will not appear on any graded question.
5.5 CSS tricks: Here, we will introduce some next level methods for making
awesome Web pages.
5.5 Recipe project: Dale walks through separating your CSS and HTML into
their own files for cleaner, easier coding.
A world of possibilities
In Week 1 we learned the basics of HTML5. It's a fairly simple format, just a
tree full of elements, which are described by tags, attributes, and the content
inside the tags; the rest is details.
Once you know the list of all the possible tags, the list of available attributes,
and a few special cases like the Document Type Declaration (DTD), self-closing
tags, and meta tags, then you will have the foundation to code in HTML5.
Putting this all together to form a coherent Web page with the addition of CSS
presents a world of possibilities. This week, we'll delve into some of those
interesting possibilities.
Tables
compound interest. Even so, tables are not obsolete, in fact HTML5
Tables are used to arrange data in tabular format - rows and columns of
cells. You can put a variety of data like text, images, forms, links and even
giving the impression that tables should be avoided at all costs. It might
seem off-putting at first, but they're not really talking about using tables for
You really don't want to use tables that way, but there absolutely nothing
wrong with using them for their intended purpose - making tables.
How about examples of table usage for layout? Let's say you have a bunch
of images you want to layout in a 3x3 grid. It is very tempting and easy to
lay them out in a table and add an image in each cell. Look at this
sitethat is laid out with CSS. You might be tempted to do this via tables
instead. Or you might want to just make your whole webpage into one big
table: site header in a table row, left navigation bar on the second row, left
column, etc.
The user must download this unnecessary presentation data for every page
they visit.
Accessibility: tables are not very screen reader friendly. Using tables
for layout will clutter your HTML making it harder for assistive technology to
presentational code that should go into CSS. To change the layout of the
page, you shouldn't be editing your content. Instead, you should just have
Tables were not intended as a layout tool, so it is best to stick to them only
Table elements
Here is a list of all the table elements we will be learning in this section:
Type Element
<table>
<caption>
<thead>, <tfoot>,
Row groups
<tbody>
Column
<colgroup>, <col>
groups
Attribute:
table.
through CSS.
1. <table border=1></table>
The code above will not provide any major visual change to your website
Note: Though there is an attribute for border, the table element should
be styled using CSS. You can use the CSS border property to do that
instead.
<caption>
It is used to give a title to the table and should be used as the first child
can also be helpful for people who have difficulty understanding the
1. <table border=1>
2. <caption>
3. <p>Table 1.0</p>
4. <p>Student's final exam results 2016</p>
5. </caption>
6. </table>
The tr, th, td, colgroup, col tags
Let's now create the most basic table with a few cells.
<tr>
standard. <th> creates table header cells. Content of table header cells is
1. <table border=1>
2. <tr>
3. <th>Name</th>
4. <th>Age</th>
5. </tr>
6. </table>
Attributes
Purpose Usage Output
for <th>
<td>
Creates table data (standard) cells. Content of table data cells is regular
1. <table border=1>
2. <tr>
3. <th scope="col">Name</th>
4. <th scope="col">Age</th>
5. </tr>
6. <tr>
7. <td>Alexa</td>
8. <td>23</td>
9. </tr>
10. <tr>
11. <td>James</td>
12. <td>35</td>
13. </tr>
14. </table>
Attributes
Purpose Usage Output
for <td>
<colgroup>
This tag allows you to group columns in a table. Grouping columns is useful
if you want to specify properties for a group of columns like applying styles
Attribute:
columns you want your colgroup to span (cover). The colgroup element
shares its attributes like style and width with all the columns it spans.
particular row.
<col>
Used within <colgroup>, the <col> tag specifies the column property for
contain is <col>.
Attribute:
Consider the table above we created using <tr>, <th> and <td>. Let's say
I want the 'name' column to be in green and the 'age' column to be orange.
You need to use the <colgroup> and <col> tags to achieve styling effects
specific to a column.
1. <body>
2. <table border=1>
3. <colgroup>
4. <col span="1" style="background-color:green">
5. <col span="1" style="background-color:orange">
6. </colgroup>
7. <tr>
8. <th>Name</th>
9. <th>Age</th>
10. </tr>
11. <tr>
12. <td>Alexa</td>
13. <td>23</td>
14. </tr>
15. <tr>
16. <td>James</td>
17. <td>35</td>
18. </tr>
19. </table>
20. </body>
<thead>
Just like how we use <colgroup> to group columns, <thead> is used to group
the header content in a HTML table.
As we learned in the previous unit, header cells are specified using <th> as a
child of <tr>. Rows specified within <thead> indicate that they are header
rows. See the code below:
1. <thead style="color:white">
2. <tr>
3. <th scope="col">Name</th>
4. <th scope="col">Age</th>
5. </tr>
6. </thead>
<tbody>
Following <thead>, subsequent rows are considered body rows in a table.
Regular cells are specified using <td> as a child of <tr>:
1. <tbody>
2. <tr>
3. <td>Alexa</td>
4. <td>23</td>
5. </tr>
6. <tr>
7. <td>James</td>
8. <td>35</td>
9. </tr>
10. <tr>
11. <td>Trisha</td>
12. <td>23</td>
13. </tr>
14. </tbody>
<tfoot>
The footer is the last to be specified and rows within <tfoot> are considered
footer rows at the end of a table:
1. <tfoot>
2. <tr>
3. <td>3 Unique Name</td>
4. <td>2 Unique Ages</td>
5. </tr>
6. </tfoot>
1. <table border=1>
2. <colgroup>
3. <col span="1" style="background-color:green">
4. <col span="1" style="background-color:orange">
5. </colgroup>
6. <thead style="color:white">
7. <tr>
8. <th scope="col">Name</th>
9. <th scope="col">Age</th>
10. </tr>
11. </thead>
12. <tbody>
13. <tr>
14. <td>Alexa</td>
15. <td>23</td>
16. </tr>
17. <tr>
18. <td>James</td>
19. <td>35</td>
20. </tr>
21. <tr>
22. <td>Trisha</td>
23. <td>23</td>
24. </tr>
25. </tbody>
26. <tfoot style="font-style: italic;">
27. <tr>
28. <td>3 Unique Names</td>
29. <td>2 Unique Ages</td>
30. </tr>
31. </tfoot>
32. </table>
Styling your table
We now know how to put a basic table together. However, the tables we have
looked at so far could really use some work in terms of how they look.
Here, we will look at some useful CSS elements to style your table. All
examples below are using JSFiddle. Each JSFiddle has three tabs - Result, HTML
and CSS. Make sure to view each tab to get the HTML and CSS code for
examples. You are also welcome to modify the code for each example by
clicking on 'Edit in JSFiddle' on the top right corner of the fiddle (click on "RUN"
when you have done your changes).
border
Though border is a valid attribute of the table element, it is best specified in
CSS. It is a shorthand property meaning you can set several CSS properties
simultaneously.
Property
Possible values
Value
border-
thin, medium, thick, in pixels
width
border-style none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset
sets the property to the default value. Defaults for width, style and color are 'medium none
initial
current-color-of-element'
separate - default value where borders are detached like in the example
above
collapse - border are collapsed into a single border
initial - sets to default value (separate)
Table width and height
Browsers automatically set the width and height for the rows and columns for
your table based on the content in your cells. Cells with most content usually
set the height and width of all cells adjacent to it.
With CSS, you can also explicitly set the dimensions of your cells. Width and
height can be specified in:
units of length like pixels, percentage - relative to the table width, etc
auto: the browser will calculate and select a width for the specified element
(default value)
It also supports initial (sets property to default value) and inherit (from parent
element).
width/height of <td> of one cell will not only affect that cell but the whole
column/row. If two cells in one column/row have different widths/heights
specified, the larger value is set.
text-align
This property is used to align the text of <th> and <td> cells left, right or center
(week 3 recap).
Default:
<th> - center
<td> - left
1. td { text-align: right;}
vertical-align
This property is used to align the text of <th> and <td> cells top, bottom or
middle.
Default:
<th> - middle
<td> - middle
1. th { vertical-align: top; }
padding
Right now our table looks quite cramped. We use the padding property
on <th> and <td> to provide some space between border and content in cell. It
takes its value in units of length like px, cm, % - relative to parent container's
width, etc.
1. th, td { padding: 15px; }
This will add 15px space around the content on all sides.
You can also apply different padding styles for four individual sides by using:
It takes two values for horizontal and vertical spacing. If only one value is
provided, it is used for both horizontal and vertical spacing:
If you try to provide spacing for only <th> and <td>, make sure there is space
from the table border or you will not see a difference.
You have to set - table { border-collapse: separate; } for it to take
effect.
Side-borders
The first property border will set a border to all four sides. You can also set
borders to individual sides - top, right, bottom, left:
1. th, td { border-right: 1px solid black; }
Activities - Tables
1.Create a simple 3x3 table with the first row containing header cells. You may
choose not to add any styling including border.
2.Create the following table with same cell content:
Attribu
Description Usage
te
Used to specify replacement text for the alt=“Test image for HTML5
alt
image course”
3.Create the following table structure using HTML and CSS following the style
as closely as possible noting table border, colors, etc. Insert dummy text values
for table.
4.Create the following table structure using HTML and CSS following the style
as closely as possible noting table border, colors, etc. Make the table cover the
entire width of the screen. Insert dummy text values for the table.
5.Find a table used in a real Web page whose table body can be scrolled.
6.Create a simple hover to highlight table that makes the background color of a
row 'yellow' when you hover over a table row.
Audio element
audio and video are new HTML 5 elements that were highly anticipated.
With HTML5 support for multimedia, this has become much easier, than
previous methods.
Audio tag
You can use the <audio> tag to embed audio in your page.
1. <audio src="sounds/flute.mp3">
2. Your browser does not support the audio file.
3. </audio>
Any text within the <audio> tags will be displayed if the browser does not
support the audio element. You should add such a message to provide
better user experience for your page as it will be viewed in all types of
The audio element has several attributes that can be used to configure
audio playback. The following table lists the audio element's attributes:
Values: <audio
src src="sounds/flute.mp3
absolute URL (file residing somewhere on the Web) "></audio>
<audio
loop Boolean attribute when specified loops media content src="sounds/flute.mp3"
controls loop></audio>
muted Boolean attribute when specified mutes media when playback <audio
begins src="sounds/flute.mp3"
controls muted></audio>
1. <audio src="http://audio.ibeat.org/content/p1rj1s/p1rj1s_-
_rockGuitar.mp3"controls loop muted preload="none">
2. Your browser does not support the audio file.
3. </audio>
If you hit play and didn't hear anything, remember that we have added
the muted attribute. So the audio will be muted when playback begins.
Just like image file formats, not all audio file formats are supported by all
browsers. You will want to use common audio file formats for browser
compatibility ensuring the highest probability that your audio file will
play.
This page under 'Browser Compatibility' lists the audio formats supported
their compression techniques that can help you decide which audio format
(eg: WAV), lossless compressed (eg: MPEG-4, WMA Lossless) and lossy
audio file. The memory used for both sound and silence is the same though
2:1.
the data and removing some audio information resulting in some loss of
quality. It is also the most popular. There are techniques in place to ensure
that the parts of sound that is lost has little effect on quality. You can also
the bigger the loss in quality and smaller the file size.
The audio format Ogg Opus has two parts to it. 'Ogg' is a digital
container file like 'Ogg' might not know how to decode it. 'Opus', the
mechanism for that stream of audio. Opus is a lossy audio coding format.
that.
The source element, also new in HTML5, serves the same purpose as
the src attribute in an audio element. It is used to specify source files for
the audio and video elements. Using the source element, you can
Example:
1. <audio controls>
2. <source src="https://courses.edx.org/asset-
v1:W3Cx+HTML5.0x+1T2016+type@[email protected]" type="audio/
wav">
3. <source src="https://courses.edx.org/asset-
v1:W3Cx+HTML5.0x+1T2016+type@[email protected]" type="audio/
mpeg">
4. Your browser does not support the audio element.
5. </audio>
if the browser doesn't support the first format, it will try the second source
file. The browser can select from the list based on its file format or codec
support. In the code snippet example above, Internet Explorer does not
support .wav files. So if you tried to play the file above in Internet Explorer,
the browser would have tried to play .wav, failed and played the .mp3
version instead.
K
Video element
Video is new in HTML5. Previously, the most reliable way to add video was
the Adobe Flash Player for example.
You can use the video element to embed video in your page. You can specify
the location of your video file using the src attribute or source element (for
multiple source files).
1. <video src="multimedia/running.mp4">
2. Your browser does not support the HTML5 video element.
3. </video>
Any text within the <video> tags will be displayed if the browser does not
support the video element. You should add such a message to provide better
user experience for your page as it will be viewed in all types of devices and
browsers.
Similar to the audio element, the video element has several attributes that
can be used to configure playback. The following table lists
the video element's attributes:
src specifies the URL or location of the media file <video src="multimedia/running.mp4"></
video>
<video src="multimedia/
Boolean attribute when specified loops media
loop running.mp4" controls loop></
content
video>
<video src="multimedia/
Boolean attribute when specified mutes media
muted running.mp4" controls muted></
when playback begins
video>
<video src="multimedia/
height, height and width of the video's play area in running.mp4" controls width="320"
width pixels. Always set height and width for a video height="240"></video>
so the browser can allocate the specified space
for it when it loads the page.
1. <video src="http://techslides.com/demos/sample-videos/small.mp4" co
ntrols loopmuted preload="none" poster="https://courses.edx.org/asset-
v1:W3Cx+HTML5.0x+2T_2016+type@[email protected]" height
="320"width="240">
2. Your browser does not support the HTML5 video element.
3. </video>
Poster attribute
The <video> tag has an important attribute that you don't find on
the audio element. The poster attribute is used to specify what picture is
shown before the video starts playing. By default, the poster shown is simply
the first frame of the video, but the poster attribute can be used to specify a
different image. It can specify a particular frame of the video or, like a real
movie poster, it can be an image that doesn't actually appear in the video.
Video file formats
Just like audio file formats, not all video file formats are supported by all
browsers. You should use common video file formats for browser compatibility
ensuring the highest probability that your video file will play.
This page under 'Browser Compatibility' lists the video formats supported by
the video element and their browser support for both desktop and mobile.
Using the source element, you will have to provide a combination of video
formats to target most browsers.
Here is some information regarding different types of video formats and their
compression techniques that can help you decide which video format to choose
apart from video element and browser compatibility:
The source element that we saw in the previous unit is also used to
specify multiple source files for the video element. The <source> tag is
if the browser doesn't support the first format, it will try the second source
file. The browser can select from the list based on its file format or codec
Attribu
Description Usage
te
<source
src="multimedia/
src Specifies the URL or location of the media file
small.mp4"></so
urce>
used to add timed text like subtitles, captions or any text you would like to
Web Video Text Tracks (WebVTT) files are the standard to include subtitles
Captions and subtitles are not the same. Subtitles are meant to translate
the language (for those who do not understand the language being spoken
in the video). Captions are meant for the deaf or people who have difficulty
hearing. It includes sound effects and other significant audio like music
and lyrics and is usually in the same language as the audio. Read more
Like the <source> tag, you can add multiple <track> tags in your
The <track> tag is self-closing and so does not require a closing tag. You
specify the <track> element as a child element of your <video> tag like
this:
<video
default It is a boolean attribute. If you have multiple src="multimedia/small.mp4"
tracks for the same video file, you can specify controls>
which one is the default using this attribute. It
can be used on one track element in a video. If <track src="captions/small-
you only have one track element, default
en.vtt" label="english" default>
</video>
<track src="captions/small-
en.vtt" label="English">
Label of the track. Browser uses the label
label value to display track options for user to
<track src="captions/small-fr.vtt"
select.
label="French">
You can download a sample video here and its corresponding WebVTT file
here. Try it in an HTML editor with the code sample above and explore
captions!
Activities - Multimedia
1.Embed an audio file in an HTML page with the following requirements:
Player has controls to play, pause, seek, etc.
Audio must automatically start playing when page loads
Audio must be muted when playback begins
2.Create an HTML audio player that plays an audio file of your choice in Google
Chrome, Internet Explorer and Mozilla Firefox. Use multiple sources if you have
to.
3.Create an HTML video player that plays a video file of your choice in Google
Chrome, Internet Explorer and Mozilla Firefox. Use multiple sources if you have
to.
4.Create a WebVTT file for this video. Then embed this video in an HTML page
with the captions you created.
Note: This section is optional material included for the curious. It will not
There are tags for all kinds of content in your Web page, text, images,
videos, animations. There's even a tag that allows you to put another
Web page in your Web page - the <iframe> tag (HTML Inline Frame
possibilities.
The popular online code editor jsfiddle has several iframes in it to display
html, css, javascript and output together. Iframes are generally used in
file (some browsers will display the file inline while some older browsers will
And we've added styling like this to get the border and drop-shadow:
1. iframe {
2. border: 10px solid red;
3. padding: .5rem;
4. margin: 1rem;
5. box-shadow: 20px 20px 10px #888888;
6. width: 355;
7. height: 200;
8. }
There is one significant problem with iframes. Suppose you create your
on the Web site foo.com. If you don't look at the URL, it might be difficult
to tell. For reasons like this, some Web sites disallow their inclusion, so if
frame and an error message in the console. This isn't a bug, it's a
feature.
There are a number of important attributes for an <iframe> tag, but for
Notes:
1. Certain Web sites like Google and Yahoo disallow embedding their
Web pages in iframes. So you will not be able to use these pages in an
iframe.
3. You can find more details about iframes from the W3C Specification.
the main page's load command until its content finishes loading. You can
slower, you can use your parent page to keep the reader occupied.
static while the other is changed - i.e. navigation menus. Helps reduce
bandwidth and server load because we can avoid loading the same content
well but you can proceed to use iframes with a notice for the reader.
external content. That content can change anytime or can upload malicious
Adding the ismap or usemap attributes to the <img> tag means that the picture
is an image with clickable areas. Imagine a picture of a world map where
different countries on the map can be clicked and it navigates to another page
like the country's wikipedia page. Simply put, we say such an image is
mapped. Here is an example of an image-map.
ismap is a boolean attribute i.e. its value is either true or false. Thus, just the
presence of the attribute indicates that it is a mapped image. To be more
precise, we say it is a server-side image-map.
An <img> tag with the src and ismap attributes creates an image with the
image source file and indicates it is a server-side image-map. How will your
code know that if you click on a part of your image, i.e. 'Australia in a world
map', it should navigate to the country's Wikipedia page? We need to create a
map file with these details and then add the location of this map file using the
anchor element. Here is a code sample:
Here, the href attribute points to the location of the map file.
The target attribute indicates where the page it navigates to should open.
'_self' will open in the same page whereas '_blank' will open it in a new tab or
window.
ismap only works if the <img> tag is used within the anchor element like in the
code above. This is important because without a link to the target map file, it
has no idea what to do with your ismap specification.
Read more about image maps on wikipedia. You might be inclined to assume
an image map will only be used for an actual map. However, there are a lot
more use cases for it. The Atlas Magazine is a good example.
Try this: Navigate to the Atlas magazine and explore the header image with a
'laughing budha' like image. The image acts as a site navigator. Clicking on
different parts of the image will bring you to different parts of the Web page.
You can use image maps in many creative ways.
Like ismap, usemap cannot be used by itself. In ismap, we used the anchor tag
to specify the map file. In usemap, we use the <area> element as a child
of <map> element to specify the coordinates and the page it should navigate
to. The usemap value should match the map element's name or id attribute.
<area> - defines the areas that can be clicked and the pages it should
navigate to. Typically takes the shape of the area, coordinates of the area, URL
of the page it should redirect to and the alt attribute (short description).
The shape attribute in the <area> tag has four values:
circle - The clickable area is a circle. You need to specify three coordinates.
E.g. coords="89,52,6". The first two is the coordinates of the circle center and
the last is the radius.
rect - The clickable area is a rectangle. You need to specify four coordinates.
E.g. coords="0,0,195,439". This is the x & y coordinates of the top left corner
and the x & y coordinates of the bottom right corner.
poly - The clickable area is a polygon of any number of sides. This shape is
very flexible and takes as many pairs of coordinates as you need to form your
polygon. E.g. coords="277,85,322,87,275,173,269,138". The last set of
coordinates can match the first set. If it doesn't, the browser will automatically
match it for you to close the polygon.
default - The clickable area is the whole image.
There are several online image map generator tools that save you the trouble
of mapping coordinates. Check them out!
Result:
Try this: Click on the left and right side of the images to check out
how usemap works :) Remember to navigate back to the course!
Note: If the <img> is inside an <a> or <button> element, clicking on it will be
interpreted as clicking on the link or button and usemap will not work.
1.How can you inform screen readers that you are using an iframe in your Web
page since iframes have poor accessibility?
2.Try the following code in your HTML editor:
1.<iframe src="http://facebook.com">
2. <p>Your browser does not support iframes.</p>
3.</iframe>
There are quite a few CSS properties for controlling borders, background
images and colors. Let's look at the most common. Take notice that as you
leverage borders and backgrounds that you will begin to see the underside of
the Web. How big is the area around a link? You might have never thought
about it before, now it'll be visible. Can we make it larger or smaller? Are these
items butted against each other? Can we space them out, or bring them closer?
We will touch on these things as well.
background-color
The background-color CSS property will fill the rectangle of the given element
with a solid background color. In addition to the values
of transparent and none, there are all the range of values that we saw
applicable to the color property.
This
<p class="p-blue">This is the list of p { background-color: #3E3F67; critt
critters } by th
<li>Ostritch</li>
</ul>
background-image
The background-image property is used to set an external image file as the
background to a particular HTML element. To bind in an external file, the value
is url, followed by an open parenthesis (, followed by a quote ", then the path,
a closing quote " and a closing parentheses ). The path can be a URL, or a
path relative from the file the CSS is in.
As these are decorative images, there are quite a few different usage scenarios
that can leverage background images. For instance, an image can be used as
repeating tile, or a background image can fit its parent element, or be a large
panoramic image not fully viewed. These scenarios can be constructed with
other CSS properties, like background-repeat, background-size,
and background-attach (as well as several others).
HTML
<p class="kitten">Women and cats will do as they please, and men and dogs should re
Heinlein</p>
background-repeat
By default, if the rectangular area of an element is bigger than the image itself,
then the image will repeat and fill the space, like tiles. For example:
CSS Result
There are advanced uses of this property. Notice in the above example, that if
the size of the parent element is not exactly a multiple of the tile, then the
image may be "cropped" and bleed off the side. That can be managed by
centering the tile (with background-position: center;). Additionally
the background-repeat property can also be used to control how it repeats.
The space value will result in no cropped images. It means "repeat, and add
space between the elements so there is no cropping". Note that this property
does not let you directly manipulate the amount of spacing. That is calculated
for you.
background-repeat: space
background-size
When not repeating, it is very useful to size a background image to fit its
element. The background-size can be used for this. There are two very
useful values: contain and cover. The contain value will put the entire
image into the space of the element, however, the space of the element may
not be completely filled if the aspect ratio of the element and the image do not
match. The cover value is the opposite. It will completely fill the element but
the image may be cropped off two opposite sides. Neither contain or cover will
distort or squish the image. Its aspect ratio is maintained.
Women and cats will do as they please, Women and cats will do as they please,
and men and dogs should relax and get and men and dogs should relax and get
used to the idea. used to the idea.
- Robert A. Heinlein - Robert A. Heinlein
The background-size property can also be used to more exactly size the
image. When used in this fashion, it takes two values separated by a space.
The first governs the width, the second the height. Examples:
The px and % units were covered in the units section. Note that other units
(rem, vh, etc) have no guarantee of support.
When specifying exact sizes, the auto value is extremely useful. It allows you
to worry only about one dimension, and then the other will handle it for you.
Otherwise there is a risk of stretching/distorting images.
Women and cats will do as Women and cats will do as Women and cats will do as
they please, and men and they please, and men and they please, and men and
dogs should relax and get dogs should relax and get dogs should relax and get
used to the idea. used to the idea. used to the idea.
- Robert A. Heinlein - Robert A. Heinlein - Robert A. Heinlein
background-position
Like background-size, background-position can be used to place or offset a
background image in the element. It takes two values (x and y) separated by a
space when used to exactly specify a position.
The most useful is the center value. It is position the center of the image in
the center of the element. This is useful even with repeating tiles.
background-position:center
Women and cats will do as they please, Women and cats will do as they please,
and men and dogs should relax and get and men and dogs should relax and get
used to the idea. used to the idea.
- Robert A. Heinlein - Robert A. Heinlein
Decorative borders and shadows
In the previous sub-section, we looked at decorative backgrounds and images.
We will continue this theme by examining decorative borders and shadows.
Like background colors, once we start using borders we will be directly facing
the underpinnings of HTML. Where does a span inside a paragraph begin and
end? How far does it extend? We'll see how the various techniques for
managing decorative CSS in the following sub-section.
border-style
p { border-style: solid; }
in
so dott dash dou groo rid outs
se
lid ed ed ble ve ge et
t
Note that the groove, ridge, inset and outset borders all use black in
addition to any explicit border-color. So if the border-color is also black
they won't be effective. Also double, groove and ridge are usually not
satisfactory on thin borders. They'll require a fat border-width.
The difference between none and hidden has to do with the sizing and
positioning of the element. An item with a hidden border is positioned as if it
had a border, but the border is not drawn. Whereas with border-style of none,
no space is allocated for the border at all.
border-color
Sets the color of the border.
border-width
Sets the width of the border. Supports a variety of units (px, em, rem ).
border abbreviations
All border styles just introduced are actually abbreviations that can be broken
out if needed. For example, here we set four different styles for a border:
p {
border-left-style: solid;
border-right-style: dotted;
border-bottom-style: dashed;
border-left-style: hidden;
}
Or, going in the other direction, the CSS property border can help abbreviate
even further. Use the formula border: <width> <style> <color>;
separating the values with spaces:
border-radius
Sometimes it seems that the whole of the World Wide Web consists of round
cornered rectangles. Join the fun by using the border-radius property:
CSS Result
.rrect { Silence is
Golden
border-width: 4px;
border-style: double;
padding: 15px;
text-align: center;
}
Note this is fun to use with a background color or background image and no
border at all:
CSS Result
.rrectbg {
background-color: beige;
text-align: center;
box-shadow
A shadow effect can be applied to the outlining rectangle of an element with
the box-shadow CSS property. The box-shadow property is typically controlled
with four values separated by spaces:
The offset values are dimension units (px, em, etc) can be positive or negative.
Positive x values place the shadow to the right, and negative values place the
shadow to the left. Similarly positive y values place the shadow vertically lower
than the element and negative values move it up.
The blur value is also a dimension unit, but can only be 0 or positive.
CSS Result
p { Urakai
text-align: center;
text-shadow
This CSS property takes the same values as box-shadow, however, the shadow
is applied directly to the text shapes:
CSS Result
These are useful properties, however, they should not be your first choice.
These CSS properties depend upon other properties before they can even be
used, and they can have unintended consequences. We'll explore them more
next week when covering Layout.
CSS Result
div {
width: 40px;
padding-top: 0;
padding-right: 1em;
padding-bottom: 10px;
padding-left: 12px;
When decorative CSS is not used by many CSS newbies, use padding like
margin, to space things out. Note: That is not correct. Margins make space
between elements and padding makes an element larger.
In this example, note that the use of padding does not make the text deviate
from the baseline. In addition, note that in the first paragraph we apply the
same padding to all four sides. However, in the second paragraph we use
different padding for different sides, thus placing the rectangle of the element
relative to the text itself.
HTML
CSS Result
My friend
span { hail from
background-color: tan;
}
.even-pad span {
padding: 15px;
.proust {
But Mssr.
France.
padding: 2px 15px 15px 2px;
.voltaire {
I'm confused - are you saying that I shouldn't use the width
property to change the width?
Essentially yes. Let's qualify that a bit so there is no confusion.
This section has been about the decorative CSS properties, like borders,
background colors, background images, and shadows. In the context of these
things users often want to make an element "bigger", or keep the border a bit
away. And in this context the padding property is absolutely the correct
property that should be used to increase the elements size. Do not use
the width or height properties for this.
"Pseudo Classes" is a fancy term for simply being able to refine our CSS
selection to something that isn't just another element. Pseudo Classes allow us
to apply styles to the different states of an element. Or to various children of
an element based on their index, or to other interactions with the browser. Best
of all, pseudo classes are easy to use.
Above us we see a tag selector (a) followed by a pseudo class, which consists
of a colon and a word (e.g.:visited ). This particular CSS rule will be applied to
any <a> tag that the user has already visited. There can be no spaces on either
side of the colon. Pseudo classes can be amended onto any CSS selector, not
just tag selectors.
:visited
a:visited { color: purple; }
:hover / :active
li:hover { background-color: red; }
li:active { background-color: green; }
The :hover pseudo class lets you change the style for an element when the
mouse is hovering above it. The :active pseudo class is applied when the
mouse is depressed into its area. Note that the mouse is rarely hovering or
clicking over/into "just one" item. At any given moment, the mouse is usually
over several elements, because if it is over a child element, it will be over the
parent, grandparent, and great grandparent. Therefore, if you have two
different style rules, such as li:hover and ul:hover, then they will both be
activated, when the mouse is over one of the list items.
Result (Try
CSS
It!)
shark
marlin
li:hover { background-color: lightblue;
}
tuna
li:active { background-color: red; }
whale
ul:active { border: 1px solid pink; }
koi
barracuda
octopus
:nth-child
tr:nth-child(odd) { background-color: lightgray; }
tr:nth-child(even) { background-color: white; }
The :nth-child pseudo class is very handy. Unlike the pseudo classes we've
seen so far, it expects a parameter. The pseudo class always ends with a pair
of parentheses with an expression inside. This expression is simply the term
odd or even, however, there are other more advanced possibilities
with mathematical equations containing the term n.
This selector is most commonly used to apply "transaction ledger" styles to
tables or lists.
Example: nth-
child(even)
shark
marlin
tuna
whale
koi
barracuda
octopus
Cursor property
li { cursor: pointer; }
Since we've broached the topic of mouse responding pseudo classes, it makes
sense to also cover the cursorCSS property.
The cursor CSS property lets you change the cursor that is displayed when the
mouse is over the element in question. This does not have to be relegated to
a :hover style, it can be applied anywhere. Though, if you want to change the
cursor when an element is depressed, set the cursor property in the context
of an :active style.
There are many possible values for the cursor property. Their exact
representation may vary slightly from browser to browser. Common values
include: default, pointer, text, move and grab. (Hover over each value to
see). In addition, some browsers support a custom image as
well ( cursor:url("images/my_pointer.png"); ).
We're also going to make the nav element move out of the way when we're not
using it, so that it only slides out when we're hovering on it.
Finally, we'll convert the Ingredients list to a table with ingredients and
amounts.
Give it a try, and when you're done (or if you get stuck), watch the video below
to see what we did.
Welcome to Week 6
Week 6 - Content
6.1 Introduction: Understanding what "layout" means to your Web
programming.
6.4 More flexbox: Main axis & cross axis, justification, alignment and order —
more flexbox concepts.
Note: This ENTIRE section is OPTIONAL.
History of layout
Over time, however, users began to prettify their documents by adjusting font
sizes and font faces. And this was primarily done in HTML itself, which caused
problems. Thus the first impetus for CSS was to separate any style information
from the HTML document itself. However, the use cases those times were all
still primarily text-based. The goals of CSS were modeled after the "master
sheets" of some word processors.
Before the first specification for CSS had been agreed upon, Web developers
began a transition to creating different types of documents. These documents
were more like fancy magazine pages - images, not text, were the centerpiece.
Decorative graphics abounded, advertisements showed up. And even as CSS2
and later CSS3 were being written, Web development changed again - Web
pages became more interactive, the term "Web application" was coined. Many
Web sites bore far more similarity to the control panel of a microwave than to a
magazine article, much less the page of a book. And finally along came smart
phones and a whole new "mobile Web" focus for Web sites, Web pages, and
Web applications.
During its short lifetime, CSS has often played "catch up" especially in respect
of layout. Here is a short list of techniques and CSS properties used historically
for layout:
Except for some basic required concepts, we are going to skip all of this and go
straight to flexbox. After many stumbles, flexbox finally brings sanity to the
much needed world of layout in CSS.
Why won't this work?
When newbie developers are groping around CSS blindly, they often stumble
upon a variety of CSS properties that could be used to alter the positioning or
size of an element such as left, top, and margin. However, when using the
properties, these developers get confused because the properties fail
to behave consistently. Sometimes the properties work, sometimes they don't,
sometimes they do the opposite of what they are doing in a different rule. We
have not covered properties like left and top yet, but we have
introduced marginand the intrepid readers may have already discovered in
their exercises that margin can have some unexpected behavior. Why is that?
The answer has to do with the two CSS properties: display and position.
The display property, in particular, has different default values for different
tags. Some tags start with display:block, and others aredisplay:inline. They
behave very differently. These two properties (display and position) often
change how an element responds to certain other layout properties. And when
this is not understood, then it may seem random to a developer struggling to
get stuff to work.
So, let's start with understanding a very important difference between block
and inline display. And that begins with the baseline.
Baseline
The text "baseline" is a key concept to understanding how the browser makes
its layout decisions.
In the image above, we see two text characters placed next to each other, the
blue line indicating the baseline. The baseline determines how and where the
characters are positioned. Note that the tail of the "g" hangs below the
baseline.
The baseline is never drawn by the browser, it is not exposed directly to you as
a developer, and CSS only may have some properties related to it.
However, the baseline governs the placement of all inline elements.
display: block versus inline
As the browser is rendering your page, every time it encounters the next tag it
has a simple question: "Do I give this element its own line?" For example,
every <p> tag gets a new line, but <a> tags do not.
This is the key distinction between the "block" level elements (like the <p>
tag) and the "inline" elements (like the <a> tag). Here is a quick table of the
default values for some of the tags we've already learned.
Inli
Block
ne
p
h1 a
div sp
an
blockquo
te q
ul i
ol b
li
Here are some differences between the block level and inline elements.
Block Level
appears below and to the left of their block level neighbors (like a carriage
return on a typewriter going to the next new line)
will expand to fill the width of the parent container by default
respects all margin properties
can have its width property set, which will make it narrower and cause its
children to wrap, but not crop. (We'll cover this later)
takes on the height of all its children (pending certain exceptions) as long as
its own height is unset. (We will cover setting the height later)
ignores the vertical-align property
Inline Elements
simply appear to the right of their preceding inline neighbor. They do not drop
to the next line unless they must "wrap".
by default, the width is simply the width of the content of the
element, plus any padding
ignore top and bottom margin settings
ignore width and height properties
are subject to vertical-align property as well as CSS white-space settings
support padding, but any padding-top or padding-
bottom does not contribute to the calculation of the height of the text line it
sits upon
cleave to the baseline where they are being placed.
The last bullet about inline elements is one of the most important to
understand. Inline elements cleave to the baseline. This is very important to
understand why inline elements are positioned vertically the way they are. It
also contributes to why they ignore top and bottom margins. Note the making
an inline element "bigger" with padding will certainly keep its neighbors away
horizontally. But if there is a neighboring text line above or below, it can only
be kept at bay with the line-height property, not margins or padding.
Below we see a span that has padding, margin-top, and background-color
applied, but no extra room is being made for it above or below, so its
background is overlapping the lines above and below.
CSS Result
span {
CSS Result
span {
inline-block
The astute reader may have spotted an obvious omission from the table of
block and inline elements above: <img> . Is <img> a block level element or
inline? If you venture to experiment you may conclude "both", and you will be
right.
For historic reasons, the <img> tag defaults to display:inline in most browsers.
If you inspect using the browsers inspector, that's what you will see. However,
it does not follow the same rules as other inline elements. In fact, regardless of
what the inspector says, images are special cased and are inline-block.
Inline-block elements still cleave to the text baseline of the line they are on. If
top or bottom margins or paddings are used, then the entire line is adjusted to
make room. (So the line-height does not need to be used.)
Here is the overlapping background style presented again, but this time
instead of using line-height to solve the problem, we simply make the span
element display:inline-block. Note that the margin-top is also respected.
CSS Result
span {
display property
At long last we arrive at the display property. We have now seen three of its
possible values: block, inline, and inline-block. There are others
(like none and flex) and we will cover them later.
.name { display: inline-block; }
Horizontal centering
Now that we've covered inline versus block display, we can intelligently discuss
centering. Let's start with inline elements.
inline
How do you center an inline element? As we recall, inline elements are
positioned along the baseline, in the natural flow of the text or content. So for
any individual inline element, there is no CSS property you can apply directly to
cause this element to center. You may apply some padding evenly or unevenly
to position its content relative to its own box. But that's not centering the
element itself.
p { text-align: center; } /* the text and any inline children of this element
will be centered */
block
How do you center a block level element? First, you may recall that block level
elements take the width of their parent by default. If the element is the same
width as its parent, it is already centered. So the first step is to limit the width
of the element. Setting the width property directly is not generally a good
practice, but we'll just do that and discuss sizing at length later.
margin magic
If set to auto, then the left and right margins will center the element. This is
the simplest and best way of centering a block level element. So the full
solution is to set the width and apply auto to the left and right margins (or to
all margins).
div { width: 200px; margin: auto; }
Position property
However, in one of the best jokes played by the authors of the CSS
specification, using those properties by themselves will have no effect on any
element. Surprisingly, most developers struggling with CSS don't find this
funny.
The reason these properties don't work by default is that they only work when
applied to positioned elements. And positioned elements are those that have
had their position property changed from the default.
'position' property
The CSS position property governs how an element is positioned on the page
and how it responds to the position adjusting properties
(left, top, right, and bottom). Up to this point in this course, we have not
used this property and so everything we've seen has been the default position,
which is position:static for all elements.
static
position: static; /* the default */
A position property of static is the default for all elements. It simply means that
all elements follow the "flowing text"model of layout and the only properties
influencing their position are margins, padding, and the display property that
selects block level layout, inline or inline-block. Static elements ignore the
positioning properties we read about earlier (left, top, right, and bottom).
fixed
position: fixed;
Therefore, for any fixed positioned element, the best practice is to ensure that
one of the horizontal positioning properties (that is, left or right) and one of
the vertical properties (top or bottom) are both set.
As a general rule, if a positioning property is being used (like left), then the
matching margin (margin-left) can also be used to additionally adjust the
position of the element. Otherwise, the margin will unlikely have any effect.
Positioned elements
We read about the positioned elements in an earlier section. There are five
positioning properties (left, top, right, bottom, and z-index) that can be
used to influence the position of an element. But these properties, by default,
will have no effect on any element. This is because all elements
are position:static by default, and static elements ignore those positioning
properties. Only positioned elements, which are elements where the position
property is set to something besides static, respect the properties.
relative
position: relative;
The relative value is exactly like static in that the "flowing text" model of layout
is setting the initial position for the element (including margins and display).
However, unlike static, elements with relative position respect the positioning
properties (left, top, right, and bottom). These properties will move the
named edge of the element from its initial position. So a value of top: 20px;
will move the top edge of the element 20 pixels further down the page.
And similarly, a value of left: 20px; will move an element 20 pixels from its
original left edge, which means move it 20 pixels to the right.
The relative position property has three primary gotchas of which you should
be aware:
Here is an example. Suppose we have two lists. We want the third item in the
list to have a background color and to be moved down by 30 pixels. Compare
what happens when we use margin-top to move it, versus a positioning
property (top). When we use top, the "Third" item appears overlapping the
Fourth and Fifth items, as they did not move at all.
margin-top top
Resu Resu
CSS CSS
lt lt
Firs Firs
t t
.third {
.third { Seco Seco
nd position: relative; nd
margin-top: 30px;
Thir top: 30px; Thir
background-color: d d
lightblue; background-color:
Four lightblue; Four
th th
}
}
Fift Fift
h h
cannot use opposite properties
When using position:relative if you use the left property you cannot also use
the right property. And, if you use the top property you cannot also use
the bottom property. If both properties are applied, then the CSS precedence
rules will determine the "winner", which is usually just the last one applied.
Again, this is unlike margins, where both margin-right and margin-left can
be meaningfully used.
margin-left left
p {
p {
Dorothea was position: Dorothea was
altogether relative; altogether
margin-left:
captivated by the captivated by the
40px;
wide embrace of wide embrace of
this conception. left: 40px; this conception.
}
}
An element that is positioned absolutely is taken out of the normal text "flow"
that governs elements positioned statically or relatively. Instead, an absolutely
positioned element is positioned by the left, top, right,
and/or bottom properties. The size or position of siblings have no effect on an
absolutely positioned element that has some positioning properties set
(left, top, etc.)
Let's take a simple example. Here we have a paragraph that contains some
text and an inner <q>. For a better illustration, the paragraph has its height set
and a border applied. The <q> is positioned absolutely.
She bethought
<p>She bethought herself now of the p { herself now of the
condemned criminal. <q>What news condemned
have you brought about the sheep- height: 200px; criminal.
stealer, uncle?</q></p>
border: 2px solid black;
q {
position: absolute;
left: 50px;
top: 50px;
background-color:
lightblue;
padding: 10px;
display: block;
width: 70px;
So that seems fairly straightforward and useful. But there are some subtle
caveats and trade-offs of which you must be wary:
In the example below, someone who did not read the section in Week 3 about
how to style list items has decided to use arbitrary numbers. There are four list
items each containing child spans which are absolutely positioned. Two of the
list items are position:relative, so the spans are positioned starting from their
rectangle. But two of the list items are position:static (the default), so the
spans are moved up to the<ul> (which is also position:relative) where they
overlap each other. (The red 1 is hidden behind the red 2). Borders have been
added in the result below, so you can easily see the rectangle
for <li> versus <ul>.
ul { position: relative;
}
<ul>
position: absolute;
<li class="rel">Fourth Fourth
<span>4</span></li> 4
left: 0px;
</ul>
top: 0px;
Therefore, for any absolutely positioned element, the best practice is to ensure
that one of the horizontal positioning properties (that is, left or right) and
one of the vertical properties (top or bottom) are set.
absolutely positioned elements do not contribute to size of
parent
Whether you realize it or not, one of the most useful default behaviors is that
the height of a parent element is automatically extended to include all its
children, its content. Designers working in CSS unconsciously lean on this fact
as they plan layouts and adjust element positions. But this is not true for
children that are positioned absolutely. Absolutely positioned children do not
contribute to the size of the parent element. A parent element that contains
only absolutely positioned children will have a height of 0, has no "measurable"
content and will behave as if it is empty.
In the example below, there are two lists (<ul>) each with a fat border. The list
on the left is normal - its children contribute to making the <ul> taller and the
fat border extends around, enclosing everything correctly. But the list items
(<li>) on the right are positioned absolutely. So those list items on the right do
not contribute to the height of the parent. As a result, it ends up with a height
of 0, as if it were empty. The fat border just becomes a fat flat line, and the list
items themselves are not enclosed.
defa absolu
ult te
First
First
Seco
Secon
nd
d
Thir
Third
d
As a general rule, if a positioning property is being used (like left), then the
matching margin (margin-left) can also be used to additionally adjust the
position of the element. Otherwise, the margin will unlikely have any effect.
'z-index' (OPTIONAL)
Note: this section is optional material included for the curious. It will not
z-index: 3;
to relative, absolute,or fixed, but not static). With the z-index you
higher. The higher the number, the more "topmost" or "overlapping" the
In the sample below, we have two lists with relatively positioned list items
The list on the left has no z-index values set, so the later elements overlap
the earlier ones. But on the right, we govern the overlapping with the z-
index property.
Res Resu
CSS CSS
ult lt
.first { z-index:
4; }
First
Seco .second { z-index: 3; First
} Seco
nd
/* no z-index set nd
Thir
*/ Third
d .third { z-index: Fourt
Four 2; } h
th
.fourth { z-index: 1;
}
This can happen because the z-index is used to figure out which sibling is
higher than another. But if two elements are not siblings, then the z-index
of their respective sibling ancestors will need to be calculated to figure out
which is higher.
Below is a simple example: there are two overlapping sibling divs, "Albert"
and "Betty". Albert has a red border and is z-index:1. Betty has a blue
Bernice are higherthan Albert and his child Alan. Albert's child Alan has a
z-index of 100, which is the highest z-index of any of them, but because
Alan's parent Albert is lower than Betty, Alan remains behind. Alan's high z-
index is only relevant to his siblings, not to cousins further out in the
document.
Res
HTML CSS
ult
<div class="betty">
We've provided you with a starter project file. The code is included below,
file (https://jsbin.com/jaserud/edit?html,css,output).
This simple file has two block level elements (the paragraphs) and two
spans, which are inline. Additionally, there are several classes defined for
you.
own line. However, the second inline span directly follows its predecessor
(via class="brect" ). When applied to the paragraphs, you can see that
the classes make the width of the paragraph stretch to the edge of the
window. It is the same as its parent width. Note that its height is no more
than its content. But the background colors and borders are tight to the
spans.
Try applying the w class to each of the elements. This class sets
the height property. Again, the paragraphs are affected, but the spans
are not.
Apply the pad class to each element. This class sets
the padding property. The paragraphs are clearly padded. The spans are
also padded, but the extra padding does not space them out. So if the
one inline element may overlap the other. Can you think of a solution
Apply the marg-vert class to each element. This class sets the top
and bottom margins. Note that it works on the block level paragraphs well
Apply the marg-horiz class to each element. This class sets the left
Play some more with the elements, trying to appreciate how block and
Try changing the HTML so that the inline elements are inside the
Have fun!
NOTE: This activity is best conducted in the Intel XDK, and uploaded to JS Bin
for discussion and feedback. Please donot upload HTML code to the
discussion forum.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Block vs Inline</title>
5. <style>
6. .u { text-decoration: underline; }
7. .brect {
8. background-color:lightblue;
9. border:1px dotted dimgray;
10. }
11. .prect {
12. background-color:lightpink;
13. border:1px dotted dimgray;
14. }
15. .w {
16. width:300px;
17. }
18. .h {
19. height:100px;
20. }
21. .pad {
22. padding:20px;
23. }
24. .marg-vert {
25. margin-top:30px;
26. margin-bottom:30px;
27. }
28. .marg-horiz {
29. margin-left:30px;
30. margin-right:30px;
31. }
32. </style>
33. </head>
34.
35. <body>
36. <p class="">He was a squyer of lowe degre</p>
37. <p class="">Will Ladislaw's mind was now wholly bent on seeing
Dorothea again, and forthwith quitting Middlemarch. </p>
38. <span class="">Ladislaw felt the awkwardness of asking for more last
words. </span>
39. <span class="u">It is certainly trying to a man's dignity to reappear
when he is not expected to do so: a first farewell has pathos in it, but to come
back for a second lends an opening to comedy</span>
40. </body>
41. </html>
The project file consists of a very long bit of prose and at the end has a
single <img> tag.
Get the cornerpiece <img> element to appear in the lower right of the
viewport. It should not scroll with the rest of the document.
That cornerpiece likely obscures any text that it overlaps. Try to get the
document text to be on top of the cornerpiece. You will have to adjust the
HTML to achieve this.
That cornerpiece is definitely a decorative graphic. Remove the <img> tag and
use decorative CSS. Again, you will have to change the HTML to achieve this.
NOTE: This activity is best conducted in the Intel XDK, and uploaded to JS Bin
for discussion and feedback. Please donot upload HTML code to the
discussion forum.
Sizing and dimensions
We have already touched on the size properties in the various discussions
about display and positioning. But here we'll cover them properly and add a
few more.
Default behavior
The default sizing behavior depends upon the display property for an element.
inline
Inline elements take the size of their content plus any padding. Additionally,
inline elements ignore any explicit sizing properties (width, height, etc.)
unless they are also position:absolute or position:fixed. This leads to a
lot of confusion when newbies are working with inline elements. If you have an
inline element whose size you want to indicate explicitly, you should probably
change it to inline-block.
inline-block
Inline-block elements also take the size of their content, plus padding.
However, they respect any explicit sizing properties. This is handy.
block
By default when no sizing properties are used, block level elements take the
width of their parent and the height of their content. Block level elements
respect any explicit sizing properties.
sizing properties
There are six sizing properties. They are
width
min-width
max-width
height
min-height
max-height
The width and height properties are a simple way to explicitly set the width or
height of an element. It is set directly, and the element maintains that
dimension (unless it is inline and ignores these properties). And certainly, when
dealing with images, there is little reason to pursue anything but the most
straightforward approach.
However, if you look again at the descriptions for inline-block and block level
elements above, you will notice that inline-block elements are sized (height
and width) to their content. And block level elements take the width of their
parent and the height of their content. So these elements are
fundamentally variably sized, and this variability is one of the most powerful
and useful aspects of these elements.
As we move into flexbox based layouts, variability in our design will become
very important.
Best practice
Unless you have good cause, try to avoid using explicit dimension properties
like width and height. If you must control the dimensions, consider using the
min- or max- variants.
Cropping and scrolling: overflow
If the element dimensions are overdetermined by the sizing properties, then its
content may not fit. In the example below, the width and height of the
paragraph have been set too small for its content. As a result, the content
overflows the rectangle of the paragraph. We've made this easier to see
by adding a border and background color to the paragraph.
This default behavior, that content that doesn't fit is shown anyway, can be
surprising if you weren't expecting it.
CSS Result
overflow
The overflow properties govern this situation. There are three related
properties: overflow, overflow-x, and overflow-y.
p { overflow: auto; }
With common text, overflowing normally only occurs in the vertical direction
(like in the example above). But if your element contains images, extremely
long words, or has adjusted CSS white spacing properties, then content can
overflow horizontally as well. The overflow property applies a common
policy to both situations, and the overflow-x and overflow-y properties let
you assign different policies for horizontal versus vertical overflow.
There are five possible values: unset, auto, visible, hidden, and scroll. In
the example below, the paragraphs are limited to a height of 100 pixels.
1.unset is both the default value when overflow has not been set and a value
that can be explicitly set.
2.The interpretation for the auto value may vary from browser to browser.
Typically, if a scroll bar is needed, it is shown, but if it is not needed, no scroll
bar is shown. In the example below, no horizontal scroll bar is needed, so none
is shown. If there was less content in the paragraph, then no scroll bar would
be shown at all.
3.When the value is scroll, then the scroll bars are always shown, whether
they are needed or not.
For a long time For a long time For a long time For a long time
For a long time
I used to go to I used to go to I used to go to I used to go to
I used to go to
bed early. bed early. bed early. bed early.
bed early.
Sometimes, Sometimes, Sometimes, Sometimes,
Sometimes,
when I had put when I had put when I had put when I had put
when I had put
out my candle, out my candle, out my candle, out my candle,
out my candle,
my eyes would my eyes would my eyes would my eyes would
my eyes would
close so close so close so close so
close so quickly
quickly that I quickly that I quickly that I quickly that I
that I had not
had not even had not even had not even had not even
even time to
time to say time to say time to say time to say
say "I'm going
"I'm going to "I'm going to "I'm going to "I'm going to
to sleep."
sleep." sleep." sleep." sleep."
The answer is that the default behavior of the browser is that the sizing
properties govern the size of the content area and any padding or borders are
"extra". But, if this is not the desired behavior, you can change it.
Every element has several "boxes" it manages: its own content, padding,
border, and margins. In CSS parlance, this question is about the "Box Model"
of the element. Here is an illustration of how the different boxes are organized
(innermost to outermost).
box-sizing
p { box-sizing: border-box; }
The box-sizing property determines how the sizing properties are applied. It
has two values: content-boxand border-box.
The content-box value is default and simply means that the height or width
properties affect the content box of the element and any padding or border is
"additional".
When border-box is used, the sizing properties are used to set the "whole"
size of the element, and the content size is likely be less.
However, if you are using the flexbox layout (which we begin in the next
section), then the box-model is not that important. The rule of thumb is that
the more you are directly managing the size of items, the more likely you will
need to change the box-sizing property to be border-box.
Up to this point, all the layout properties we've looked at have all applied to
an individual element. But performing layout tasks like columnar layout or
anything responsive requires coordinating multiple elements. This is where
the flexbox comes in. When working with flexbox layout, there are some CSS
properties that are applied to a parent element (also known as the flex
container) and other CSS properties that are applied to the direct children of
that parent (also known as the flex items). The flex container will handle laying
out of its children. And, best of all, the flex container will lay out its children
smartly, making the best use of the screen size available to it, while still
following the general guidelines you laid down for it. As a general rule, layout
with flexbox is pretty easy and the results are great. So let's get started.
the minimum
The minimum scenario for using flexbox is to make use of two CSS rules, and
better results are achieved with a third.
1.display:flex; on the flex container
2.flex:1; on the flex items (the children of the flex container)
3.(better) flex-flow: row wrap; on the flex container.
flex container
div { display: flex; }
span { display: inline-flex; }
Flexbox containers can lay out their children both horizontally, as in a row, and
vertically, as in a column, and both at the same time. This means that a single
flex container not only can help you lay out a three column design, but also
handle the header and footer above and below. (Did we mention that flexbox
rocks?)
But the flexbox container does need a starting rule to follow. Do you want it to
primarily line things up horizontally like a row? Or vertically like a column? And
will you be wanting that row or column to wrap? The flex-flow property lets
you specify both of those things.
The possible values for the flex-direction are: row, row-reverse, column,
and column-reverse.
The values for the flex-wrap part are: wrap, wrap-reverse, and nowrap.
There are more properties that we can apply to a flex container and we'll look
at them in the upcoming sections. But these two will take care of most of what
you might want.
flex items
The direct children of a flex container are automatically converted into flex
items, with the exception of children that are position-fixed or position-
absolute, which are taken out of the "flow" of the flex container. So there is no
property needed to designate a child as a flex item, as it happens
automatically.
One other automatic behavior to be aware of is that empty flex items are
automatically removed from the flex container. Keep that in mind if you were
planning on using an empty <div></div> construct as a placeholder for a CSS
background image.
There is an array of flex item properties that can be applied to the children of a
flex container, but there are three that we are not supposed to use in isolation.
These three are: flex-grow, flex-shrink, and flex-basis.These three
properties interrelate, so rather than using them in isolation the CSS3
specification encourages us to use the flex property, which can act as an
abbreviation for all the three.
flex property
Earlier, we saw that display:flex; can be used to designate a parent element
as a flex container. In that case, the symbol "flex" is used as a value of
the display property.
But flex is also the name of a property. It is a property that is applied to flex
items, the children of a flex container.
flex-grow
p { flex: 1; /* rather than use flex-grow, use flex: <flex-grow>; */ }
A larger flex-grow value does not necessarily mean that an element is larger
than its siblings that have smaller flex-grow values. The content of each
sibling is first accounted for by the flex container when creating any row or
column and only after that has been settled is any extra space distributed
among the children.
Setting the flex-grow to 0 will prevent the flex item from growing. But
remember, that will cause the item to shed its "flexible size" super-power.
flex-shrink
p { flex: 1 1; /* rather than use flex-shrink directly, use flex: <flex-grow><flex-
shrink> */ }
The flex-shrink is the opposite of flex-grow. When laying out any row or
column, if the flex container needs to take away some space from the children,
then those with the highest flex-shrink values contribute more of the needed
space. Again, the flex-shrink value is just a number and it only has meaning
when compared to its sibling flex-shrink values. And, again, this only occurs
in the situation where the flex-container might need some space from its
children.
Note: Like flex-grow, setting the flex-shrink to 0 will prevent the flex item
from shrinking. However, this may not be as desirable as it first seems.
Remember the box model from the previous section? If an item flex-
shrink value is 0, then its border or padding may end up off-screen or pushed
out of the parent, because there is a difference between "fitting" and "fitting
nicely", and without the ability to be shrunk an item might fit but not "fit
nicely". If you must set flex-shrink to 0, then it is recommended that you
also set the box-sizing to border-box.
flex-basis
p { flex: 1 1 87px; /* use flex: <flex-grow> <flex-shrink> <flex-basis> */}
The flex-basis can be used instead of the sizing properties on a flex item. If
the flex-direction of the parent flex container is row or row-reverse, then
the flex-basis will govern the width of the flex item. If the flex-
direction is column or column-reverse, it governs the height.
The flex-basis provides the starting dimension (width or height) for the flex-
item. It may be grown or shrunk from that. If you do not want it to change at
all, then set the flex-grow and flex-shrink to 0, and the box-
sizing to border-box. However, this is not advisable. Read the flex-
shrink discussion above.
Here are some quick tips to help you get the most
out of flexbox.
Remember the minimum
If you have a parent element that contains some child elements, then
putting display:flex; on the parent is all that is needed to get started. The
parent itself behaves like a normal block level element, it is the flex container,
and all of its children are flex items.
It's not a bad idea to specify the flex-flow for the flex container (flex-
flow: row wrap;), but it isn't required.
It's generally a good idea to also initialize the flex property on the flex items
(e.g. flex:1), but again, this isn't required.
Doing so will make your flex items a bit more malleable. In CSS professional
parlance, this is called being "responsive".
Remember also, that if you overdetermine the dimensions for an element, then
you may also have to start managing its overflow setting and its box model.
Who needs more worry? Underconstraining is the path to happiness.
The project file that is used in this demonstration can be downloaded directly.
The file we edit is www/index.html
The final version is also available for download. Both are project files that can
be opened in the Intel® XDK.
Semantic sections
You may recall from week 2 several semantic tags for denoting the different
parts of a page:
header
footer
aside
article
main
section
nav
Several of those tags like <header>, <footer>, and <aside> have tantalizingly
promising names that suggest they provide some sort of layout
assistance. However, the HTML5 newcomer may be disappointed to discover
that those tags are just basic block level elements, functioning no different
than <p> or <div>. Flexbox comes to the rescue and helps those tags realize
their potential.
HTML
<body>
<header>the header</header>
<aside>first column</aside>
<footer>the footer</footer>
</body>
NOTE: A better practice is to use longer text content for the dummy text. This
will help us verify sizing and scrolling, etc. Instead of a simple text like "first
column", insert a long paragraph of text.
Step 2 - surround with flexbox container
Our five tags will be the flexbox items. They need to be nested in a flexbox
container. So we'll surround them with a simple div, since the flexbox
container serves no semantic purpose - it is only used to achieve a layout goal,
and we'll apply a class to the div so we can easily apply the CSS we want.
HTML
<body>
<div class="fc">
<header>the header</header>
<aside>first column</aside>
<footer>the footer</footer>
</div>
</body>
CSS Result
body { margin:0px; }
.fc > * {
margin: 10px;
padding: 20px;
background-color:
lightgray;
border-radius: 10px;
CSS Result
.fc {
display: flex;
flex-flow: row
wrap;
.fc > * {
flex: 1;
Either approach will work, though if you go with the first approach you might
also need to set the box-sizing property to be border-box. We'll use the flex-
basis, since that is simpler and participatory.
Since this is the layout for the entire page, we'll use the vw units to set the
width to be 100 percent of the viewport width.
CSS Result
.fc header,
.fc footer {
flex: 0 1
100vw;
So how can we get that footer down there when there isn't enough content?
Think for a minute about this before continuing to read.
...[thinking]...
Have you figured it out? The solution is simple: just make the minimum height
of the flex container be the viewport height.
CSS Result
For reference, here is the final CSS, with comments. This does not include the
visualization CSS for the background colors and rounded corners.
CSS
.fc {
display: flex;
.fc > * {
flex: 1;
}
/* header and footer should be full width */
.fc header,
.fc footer {
flex: 0 1 100vw;
BUT, reflect for a moment: if the header and the footer are full width and they
are fixed height, what is the flexbox container doing for them? Are they
participating in the layout of their siblings in any way? They are not. If the
header and footer are set to a constant height and the width of the viewport,
they don't need any help from the flexbox container. So, in this case, the
solution is to remove them from the flexbox.
The only trick is that we must also adjust the height of the flexbox container. It
is no longer the full height of the viewport. Instead, it is the full height of the
viewport minus the combined height of the header and footer. For that, we'll
use calc()
HTML CSS
<header>the header</header> */
<aside>first column</aside>
Result
Download
You are encouraged to follow these steps yourself. It is very satisfying seeing
everything come together step by step. But the two completed versions are
available for direct download.
Holy Grail Variable Height Header and Footer
Holy Grail Fixed Height Header and Footer
For both of these projects, the file to edit is www/index.html. They can also be
opened directly by the Intel® XDK.
Optional: if you'd like to participate in dn's JS Bin experiment, you may view,
download, or clone these two completed versions:
How might you do this? Experiment and see if you can figure it out. (Answer
below).
Try to lay out something like this, where the header is a narrow column on the
left and the footer is a narrow column on the right.
Some notes:
Enjoy the process of exploring. This ninety degree change is challenging. If you
get stuck, there is a solution you can directly download here.
Optional: if you'd like to participate in dn's JS Bin experiment, you may view,
download, or clone the HTML5.0 6.3.8 Flexbox columns completed
version (http://jsbin.com/jidiko/edit?html,css,output).
NOTE: This activity is best conducted in the Intel XDK, and uploaded to JS Bin
for discussion and feedback. Please donot upload HTML code to the
discussion forum.
Main and cross axes (OPTIONAL)
Note: This material is included for completeness. However, many are able to
use flexbox satisfactorily without it. None of the material here will appear in
any graded question.
Concepts
Before we step deeper into flexbox, there are a few concepts we should make
sure to understand.
Main axis and cross axis
Every flexbox has two axes. The "main" axis is the major axis along which all
the flex items are being laid. So, when the flex-direction is row, the main
axis is horizontal, running left to right. When the flex-direction is column,
the main axis is vertical, running top to bottom. (Quick quiz: what if the flex-
direction is row-reverse?).
The "cross" axis runs perpendicular to the main axis. It is the direction that
items might wrap. So with flex-flow: row wrap; the cross axis is vertical and
runs top to bottom. And with flex-flow:row wrap-reverse; it is vertical running
bottom to top.
Start and end
In the illustration above, we see the main and cross axes as they would be
for flex-flow:row wrap;. And in the same illustration, we also see the start and
end points for both the main and cross axes. Take a moment and visualize
how both the axes and the start and end points would change for each of these
combinations for flex-flow :
row wrap
row wrap-reverse
row-reverse wrap
row-reverse wrap-reverse
column wrap
column wrap-reverse
column-reverse wrap
column-reverse wrap-reverse
main axis for sizing, cross axis for alignment
The terms "main" and "cross" appear in the descriptions of flexbox and
in multiple online tutorials you might find. However, they are not used in the
names of any CSS properties or values. The following properties control
behavior along the main axis. We are already familiar with all of them,
except justify-content.
flex
flex-grow
flex-shrink
flex-basis
justify-content
All the properties above control how a flex item might be sized,
except justify-content, which controls how a flexbox container spaces out
and positions flex items.
And, obversely, the following list of properties controls behavior along the cross
axis:
align-content
align-items
align-self
These properties all govern how a flex item might be aligned or positioned
along the cross axis. They also support a simple stretch value, which we will
see when we cover them.
Important: Flexbox items can have their size and position influenced on the
main axis, with flex-grow, and others. But on the cross axis, with the
exception of a coarse stretch option, we can only influence their position.
This distinction is very important. In the cross axis direction, our ability to
influence the sizing is limited. When not using stretch, we get the
normal sizing behavior (block level elements take vertical size of content, etc.)
or use the regular sizing properties (min-height, max-height, height, etc.)
justify-content
.fc { justify-content: space-around; }
When all the flex items in a flexbox container are fully resizable, then there will
not be any extra space to put between the items. However, when the flex
items are fixed size, or cannot grow anymore, then the flexbox container will
put the extra space between or outside the items. The closest analogue from
typography is called "justifying". Thus, the justify-content property serves a
similar function for flexbox containers.
The table below should help illustrate this. It shows the justification options for
a flexbox container with flex-flow:row;
ite
flex-start m
ite
m
ite
m
ite
m
ite
center
m
ite
m
ite
m
ite
flex-end
m
ite
m
ite
m
space- ite
between m
ite
m
ite
m
space- ite
around m
ite
m
If the flex-direction were row-reverse, then the only thing to change in the
table above would be that the appearances of flex-start and flex-end would
be reversed.
align-items
.fc { align-items: stretch; }
The align-items determines how items are aligned in the cross axis
direction. This is applied to the flexbox container. The possible values
are stretch, flex-start, flex-end, center, and baseline. In the context of
alignment, flex-start and flex-end refer to the cross start and cross end
sides, which may be swapped if the flex-wrap:wrap-reverse option is elected.
align-items defaults to stretch, if it is not set. The table below should help
illustrate this. It shows a flex container with flex-flow:row; and a min-
height value that is greater than the height of any of the items.
In the example below, each item has a different line-height value, so you
can see how they align to each other.
Notes
stretch it stretch will not work on flex items that have a fixed dimension. Use min-width or min-
height instead of width or height, if you want the item to actually stretch.
e
it
e
it
flex- it
start
e
it
it
e
m
it
it
center
m
it
flex- it
end
e
it
e
it
baselin it
e
e
it
it
e
m
align-content
.fc { align-content: space-between; }
Notes
it
stretch stretch will not work on flex items that have a fixed dimension. Use min-width or min-
e
height instead of width or height, if you want the item to actually stretch.
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
flex-start e
m
it
e
m
it
e
m
it
e
m
it
center
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
flex-end
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
space-
e
between
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
e
m
it
space-
e
around
m
it
e
m
it
e
m
it
e
m
align-self
.item { align-self: center; }
In the example below, we have a flex container with flex-flow:row; and align-
items:center;. The individual items have their align-self property set.
align-
Notes
self
item
item
stretc
h
flex-
start
cente stretch will not work on flex items that have a fixed dimension. Use min-width or min-height
r instead of width or height, if you want the item to actually stretch.
flex-
end
baseli
ne
item
item
Order (OPTIONAL)
Note: This material is included for completeness. However, many are able to
use flexbox satisfactorily without it. None of the material here will appear in
any graded question.
One of the most exciting flexbox properties is also its simplest: order.
.item { order: 2; }
The order property allows you to determine the order in which the item
appears in the flexbox. This allows you to present the information in the
flexbox layout independent of its order in the HTML itself. This is very useful, as
there are many factors competing to drive the order of an HTML file.
For example, semantically, for SEO (Search Engine Optimization), and for
accessibility for disabled visitors, the best practice is to put the title of an
article before the article itself. While that seems simple enough, if your flexbox
layout uses a flex-direction value of column-reverse, this could be a
problem.
The order property, when applied to an individual flexbox item, lets you set its
order. By default, the first item in a flexbox container has the order value of 1,
the second is 2, etc. And you can override it.
Resul
HTML CSS
t
<div class="fc">
.four { order: 1;
}
<p class="one">One</p> On
e
.two { order: 2;
<p class="two">Two</p>
}
Tw
<p o
.one { order: 3;
class="three">Three</p>
}
Thr
<p class="four">Four</p> ee
.three { order: 4;
}
</div>
This week, we'll put to use some of the layout techniques that we've learned.
We'll improve our Web page by making it more responsive, so it's easily
readable whether wide or narrow. And we'll fix the banner and nav element in
place, so it's always where we need it.
Give it a try, then watch the video below and see what we did.
Good luck!
Congratulations!
Below are not topics that you must learn, only areas of interest that you could
learn more about if you are inclined to do so. Most of them are covered in the
other W3Cx HTML5 courses, part of the "HTML5 from W3C" XSeries. We
encourage you to enroll in:
JavaScript
JavaScript is a programming language that will run in your Web pages. If you
want to make interactive pages with buttons or forms that cause things to
happen, JavaScript is the next technology to learn.
Forms
There are series of HTML tags for making on-page Web forms. ( <form>,
<fieldset>, <input>, <button> and others). If you want a search box or a log-
in control, then the form tags are worth exploring. On their own, they are very
simple. But to make them function you'll need JavaScript or at least some
server side development.
More CSS
There are nearly 300 CSS properties in the CSS3 specification. We did not cover
them all in this course. Areas of possible interest include CSS Transformations,
CSS Animations, and media queries.
Happy exploring!
Essential background
Accessibility Overview
Introduction to Web Accessibility
How People with Disabilities Use the Web
Business Case for Web Accessibility
Accessibility Standards
Web Content Accessibility Guidelines (WCAG) Overview
Authoring Tool Accessibility Guidelines (ATAG) Overview
User Agent Accessibility Guidelines (UAAG) Overview
Accessible Rich Internet Applications (WAI-ARIA) Overview