HTML Css Js
HTML Css Js
HTML Css Js
What is HTML?
HTML stands for Hyper Text Markup Language
HTML is the standard markup language for creating Web pages
HTML describes the structure of a Web page
HTML consists of a series of elements
HTML elements tell the browser how to display the content
HTML elements label pieces of content such as "this is a heading",
"this is a paragraph", "this is a link", etc.
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
Example Explained
The <!DOCTYPE html> declaration defines that this document is an
HTML5 document
The <html> element is the root element of an HTML page
The <head> element contains meta information about the HTML page
The <title> element specifies a title for the HTML page (which is
shown in the browser's title bar or in the page's tab)
The <body> element defines the document's body, and is a container
for all the visible contents, such as headings, paragraphs, images,
hyperlinks, tables, lists, etc.
The <h1> element defines a large heading
The <p> element defines a paragraph
Note: Some HTML elements have no content (like the <br> element). These
elements are called empty elements. Empty elements do not have an end tag!
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
It must only appear once, at the top of the page (before any HTML tags).
<!DOCTYPE html>
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least
important heading:
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
Example
HTML Images
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are
provided as attributes:
Example
<img src="cat.jpg" alt="Cat" width="104" height="142">
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example Explained
The <html> element is the root element and it defines the whole HTML
document.
It has a start tag <html> and an end tag </html>.
<body>
</body>
Example
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
The <br> tag defines a line break, and is an empty element without a
closing tag:
Example
3. Attributes
HTML attributes provide additional information about HTML
elements.
HTML Attributes
All HTML elements can have attributes
Attributes provide additional information about elements
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"
There are two ways to specify the URL in the src attribute:
Tip: It is almost always best to use relative URLs. They will not break if
you change domain.
Example
Example
Example
See what happens if we try to display an image that does not exist:
<img src="img_typo.jpg" alt="Girl with a jacket">
Example
<!DOCTYPE html>
<html lang="en">
<body>
...
</body>
</html>
The value of the title attribute will be displayed as a tooltip when you
mouse over the element:
Example
NB: The title attribute (and all other attributes) can be written with
uppercase or lowercase like title or TITLE.
In some situations, when the attribute value itself contains double quotes,
it is necessary to use single quotes:
Or vice versa:
Chapter Summary
All HTML elements can have attributes
The href attribute of <a> specifies the URL of the page the link goes
to
The src attribute of <img> specifies the path to the image to be
displayed
The width and height attributes of <img> provide size information for
images
The alt attribute of <img> provides an alternate text for an image
The style attribute is used to add styles to an element, such as
color, font, size, and more
The lang attribute of the <html> tag declares the language of the
Web page
The title attribute defines some extra information about an
element
Exercise:
Add a "tooltip" to the paragraph below with the text "About W3Schools".
4. HTML Headings
HTML headings are titles or subtitles that you want to display on
a webpage.
Example
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least
important heading.
Example
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
Note: Use HTML headings for headings only. Don't use headings to make
text BIG or bold.
Bigger Headings
Each HTML heading has a default size. However, you can specify the size
for any heading with the style attribute, using the CSS font-
size property:
Example
5. HTML Paragraphs
A paragraph always starts on a new line, and is usually a block
of text.
HTML Paragraphs
The HTML <p> element defines a paragraph.
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Display
You cannot be sure how HTML will be displayed.
Large or small screens, and resized windows will create different results.
With HTML, you cannot change the display by adding extra spaces or
extra lines in your HTML code.
The browser will automatically remove any extra spaces and lines when
the page is displayed:
Example
<p>
This paragraph
contains a lot of lines
in the source code,
but the browser
ignores it.
</p>
<p>
This paragraph
contains a lot of spaces
in the source code,
but the browser
ignores it.
</p>
Example
The <hr> tag is an empty tag, which means that it has no end tag.
Use <br> if you want a line break (a new line) without starting a new
paragraph:
Example
The <br> tag is an empty tag, which means that it has no end tag.
Example
<p>
My Bonnie lies over the ocean.
Example
<pre>
My Bonnie lies over the ocean.
Exercise:
Use the correct HTML tag to add a paragraph with the text "Hello World!".
<html>
<body>
<!-- //-->
</body>
</html>
6. HTML Styles
The HTML style attribute is used to add styles to an element,
such as color, font, size, and more.
Example
I am Red
I am Blue
I am Big
The HTML Style Attribute
Setting the style of an HTML element, can be done with
the style attribute.
<tagname style="property:value;">
Background Color
The CSS background-color property defines the background color for an
HTML element.
Example
Set the background color for a page to powderblue:6
<body style="background-color:powderblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
Example
Set background color for two different elements:
<body>
</body>
Text Color
The CSS color property defines the text color for an HTML element:
Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
Fonts
The CSS font-family property defines the font to be used for an HTML
element:
Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
Text Size
The CSS font-size property defines the text size for an HTML element:
Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
Text Alignment
The CSS text-align property defines the horizontal text alignment for an
HTML element:
Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
Chapter Summary
Use the style attribute for styling HTML elements
Use background-color for background color
Use color for text colors
Use font-family for text fonts
Use font-size for text sizes
Use text-align for text alignment
Exercise:
Use the correct HTML attribute, and CSS, to set the color of the
paragraph to "blue".
HTML Text
7.
Formatting
HTML contains several elements for defining text with a special
meaning.
Example
This text is bold
This text is italic
This is subscript and superscript
Example
<b>This text is bold</b>
The HTML <strong> element defines text with strong importance. The
content inside is typically displayed in bold.
Example
<strong>This text is important!</strong>
HTML <i> and <em> Elements
The HTML <i> element defines a part of text in an alternate voice or
mood. The content inside is typically displayed in italic.
Tip: The <i> tag is often used to indicate a technical term, a phrase from
another language, a thought, a ship name, etc.
Example
The HTML <em> element defines emphasized text. The content inside is
typically displayed in italic.
Tip: A screen reader will pronounce the words in <em> with an emphasis,
using verbal stress.
Example
Example
<small>This is some smaller text.</small>
Example
<p>Do not forget to buy <mark>milk</mark> today.</p>
Example
Example
Example
<p>This is <sub>subscripted</sub> text.</p>
Example
Exercise:
Add extra importance to the word "degradation" in the paragraph below.
<p>
WWF's mission is to stop the degradation of our planet's
natural environment.
</p>
*Week 2:*
8. HTML Comments
HTML comments are not displayed in the browser, but they can
help document your HTML source code.
HTML Comment Tag
You can add comments to your HTML source by using the following
syntax:
Notice that there is an exclamation point (!) in the start tag, but not in
the end tag.
Note: Comments are not displayed by the browser, but they can help document
your HTML source code.
Add Comments
With comments you can place notifications and reminders in your HTML
code:
Example
<!-- This is a comment -->
<p>This is a paragraph.</p>
Hide Content
Comments can be used to hide content.
Example
<p>This is a paragraph.</p>
Example
Hide a section of HTML code:
<p>This is a paragraph.</p>
<!--
<p>Look at this cool image:</p>
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->
<p>This is a paragraph too.</p>
Comments are also great for debugging HTML, because you can comment
out HTML lines of code, one at a time, to search for errors.
Example
Exercise:
Use the HTML comment tag to make a comment out of the "This is a
comment" text.
<h1>This is a heading</h1>
This is a comment
<p>This is a paragraph.</p>
9. HTML Colors
HTML colors are specified with predefined color names, or with
RGB, HEX, HSL, RGBA, or HSLA values.
Color Names
In HTML, a color can be specified by using a color name:
Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray
Background Color
You can set the background color for HTML elements:
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Example
Text Color
You can set the color of text:
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.
Example
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>
Border Color
You can set the color of borders:
Hello World
Hello World
Hello World
Example
Color Values
In HTML, colors can also be specified using RGB values, HEX values, HSL
values, RGBA values, and HSLA values.
The following three <div> elements have their background color set with
RGB, HEX, and HSL values:
Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>
To display black, set all color parameters to 0, like this: rgb(0, 0, 0).
To display white, set all color parameters to 255, like this: rgb(255, 255,
255).
Shades of Gray
Shades of gray are often defined using equal values for all three
parameters:
#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values
between 00 and ff (same as decimal 0-255).
To display black, set all color parameters to 00, like this: #000000.
To display white, set all color parameters to ff, like this: #ffffff.
<h1 style="background-color:#ff0000;">#ff0000</h1>
<h1 style="background-color:#0000ff;">#0000ff</h1>
<h1 style="background-color:#3cb371;">#3cb371</h1>
<h1 style="background-color:#ee82ee;">#ee82ee</h1>
<h1 style="background-color:#ffa500;">#ffa500</h1>
<h1 style="background-color:#6a5acd;">#6a5acd</h1>
Shades of Gray
Shades of gray are often defined using equal values for all three
parameters:
<h1 style="background-color:#404040;">#404040</h1>
<h1 style="background-color:#686868;">#686868</h1>
<h1 style="background-color:#a0a0a0;">#a0a0a0</h1>
<h1 style="background-color:#bebebe;">#bebebe</h1>
<h1 style="background-color:#dcdcdc;">#dcdcdc</h1>
<h1 style="background-color:#f8f8f8;">#f8f8f8</h1>
9(iii). HTML HSL and
HSLA Colors
HSL stands for hue, saturation, and lightness.
Saturation
Saturation can be described as the intensity of a color.
50% is 50% gray, but you can still see the color.
Lightness
The lightness of a color can be described as how much light you want to
give the color, where 0% means no light (black), 50% means 50% light
(neither dark nor light), and 100% means full lightness (white).
Example
Shades of Gray
Shades of gray are often defined by setting the hue and saturation to 0,
and adjusting the lightness from 0% to 100% to get darker/lighter
shades:
Example
Note: A link does not have to be text. A link can be an image or any other
HTML element!
The most important attribute of the <a> element is the href attribute,
which indicates the link's destination.
The link text is the part that will be visible to the reader.
Clicking on the link text, will send the reader to the specified URL address.
Example
Tip: Links can of course be styled with CSS, to get another look!
Example
Tip: Links can of course be styled with CSS, to get another look!
Example
A local link (a link to a page within the same website) is specified with
a relative URL (without the "https://www" part):
Example
<h2>Absolute URLs</h2>
<p><a href="https://www.w3.org/">W3C</a></p>
<p><a href="https://www.google.com/">Google</a></p>
<h2>Relative URLs</h2>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/default.asp">CSS Tutorial</a></p>
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>
Example
Button as a Link
To use an HTML button as a link, you have to add some JavaScript code.
Example
<button onclick="document.location='default.asp'">HTML
Tutorial</button>
Link Titles
The title attribute specifies extra information about an element. The
information is most often shown as a tooltip text when the mouse moves
over the element.
Example
Example
Example
Link to a page located in the html folder on the current web site:
Example
Link to a page located in the same folder as the current page:
Chapter Summary
Use the <a> element to define a link
Use the href attribute to define the link address
Use the target attribute to define where to open the linked
document
Use the <img> element (inside <a>) to use an image as a link
Use the mailto: scheme inside the href attribute to create a link
that opens the user's email program
Example
Here, an unvisited link will be green with no underline. A visited link will be
pink with no underline. An active link will be yellow and underlined. In
addition, when mousing over a link (a:hover) it will become red and
underlined:
<style>
a:link {
color: green;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: pink;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: red;
background-color: transparent;
text-decoration: underline;
}
a:active {
color: yellow;
background-color: transparent;
text-decoration: underline;
}
</style>
Link Buttons
A link can also be styled as a button, by using CSS:
This is a link
Example
<style>
a:link, a:visited {
background-color: #f44336;
color: white;
padding: 15px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a:hover, a:active {
background-color: red;
}
</style>
To create a bookmark - first create the bookmark, then add a link to it.
When the link is clicked, the page will scroll down or up to the location
with the bookmark.
Example
First, use the id attribute to create a bookmark:
Then, add a link to the bookmark ("Jump to Chapter 4"), from within the
same page:
Example
<a href="#C4">Jump to Chapter 4</a>
Chapter Summary
Use the id attribute (id="value") to define bookmarks in a page
Use the href attribute (href="#value") to link to the bookmark
Exercise:
Use the correct HTML to make the text below into a link to "default.html".
Example
<img src="pic_trulli.jpg" alt="Italian Trulli">
Example
<img src="img_girl.jpg" alt="Girl in a jacket">
Example
<img src="img_chania.jpg" alt="Flowers in Chania">
Images are not technically inserted into a web page; images are linked to
web pages. The <img> tag creates a holding space for the referenced
image.
The <img> tag is empty, it contains attributes only, and does not have a
closing tag.
Syntax
Note: When a web page loads, it is the browser, at that moment, that
gets the image from a web server and inserts it into the page. Therefore,
make sure that the image actually stays in the same spot in relation to
the web page, otherwise your visitors will get a broken link icon. The
broken link icon and the alt text are shown if the browser cannot find the
image.
Example
Example
Example
<img src="wrongname.gif" alt="Flowers in Chania">
Tip: A screen reader is a software program that reads the HTML code, and
allows the user to "listen" to the content. Screen readers are useful for people
who are visually impaired or learning disabled.
Example
The width and height attributes always define the width and height of the
image in pixels.
Note: Always specify the width and height of an image. If width and height are
not specified, the web page might flicker while the image loads.
Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 100%;
}
</style>
</head>
<body>
</body>
</html>
Example
Example
Animated Images
HTML allows animated GIFs:
Example
Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag:
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>
Image Floating
Use the CSS float property to let the image float to the right or to the
left of a text:
Example
Chapter Summary
Use the HTML <img> element to define an image
Use the HTML src attribute to define the URL of the image
Use the HTML alt attribute to define an alternate text for an image,
if it cannot be displayed
Use the HTML width and height attributes or the
CSS width and height properties to define the size of the image
Use the CSS float property to let the image float to the left or to
the right
Note: Loading large images takes time, and can slow down your web page. Use
images carefully.
HTML Exercises
Exercise:
Use the HTML image attributes to set the size of the image to 250 pixels
wide and 400 pixels tall.
HTML Background
12.
Images
A background image can be specified for almost any HTML
element.
Example
Add a background image on a HTML element:
You can also specify the background image in the <style> element, in
the <head> section:
Example
Example
<style>
body {
background-image: url('img_girl.jpg');
}
</style>
Background Repeat
If the background image is smaller than the element, the image will
repeat itself, horizontally and vertically, until it reaches the end of the
element:
Example
<style>
body {
background-image: url('example_img_girl.jpg');
}
</style>
To avoid the background image from repeating itself, set the background-
repeat property to no-repeat.
Example
<style>
body {
background-image: url('example_img_girl.jpg');
background-repeat: no-repeat;
}
</style>
Background Cover
If you want the background image to cover the entire element, you can
set the background-size property to cover.
This way, the background image will cover the entire element, with no
stretching (the image will keep its original proportions):
Example
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
Background Stretch
If you want the background image to stretch to fit the entire element,
you can set the background-size property to 100% 100%:
Try resizing the browser window, and you will see that the image will
stretch, but always cover the entire element.
Example
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
</style>
12(i).
HTML <picture> Elem
ent
The HTML <picture> element allows you to display different
pictures for different devices or screen sizes.
Each <source> element has a media attribute that defines when the image
is the most suitable.
Example
1. Bandwidth
If you have a small screen or device, it is not necessary to load a large
image file. The browser will use the first <source> element with matching
attribute values, and ignore any of the following elements.
2. Format Support
Some browsers or devices may not support all image formats. By using
the <picture> element, you can add images of all formats, and the
browser will use the first format it recognizes, and ignore any of the
following elements.
Example
<picture>
<source srcset="img_avatar.png">
<source srcset="img_girl.jpg">
<img src="img_beatles.gif" alt="Beatles" style="width:auto;">
</picture>
Note: The browser will use the first <source> element with matching attribute
values, and ignore any following <source> elements.
HTML Image Tags
Tag Description
What is CSS?
CSS stands for Cascading Style Sheets
CSS describes how HTML elements are to be displayed on screen,
paper, or in other media
CSS saves a lot of work. It can control the layout of multiple web
pages all at once
External stylesheets are stored in CSS files
CSS Example
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p {
font-family: verdana;
font-size: 20px;
}
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of
large websites, where fonts and color information were added to every
single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created
CSS.
With an external stylesheet file, you can change the look of an entire
website by changing just one file!
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want
to style.
Example
Here, all <p> elements on the page will be center-aligned, with a red text
color:
p {
text-align: center;
color: red;
}
Example
The CSS rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
}
Example
In this example all HTML elements with class="center" will be red and center-
aligned:
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected
by a class.
Example
In this example only <p> elements with class="center" will be red and
center-aligned:
p.center {
text-align: center;
color: red;
}
Example
Example
The CSS rule below will affect every HTML element on the page:
* {
text-align: center;
color: blue;
}
Look at the following CSS code (the h1, h2, and p elements have the
same style definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}
<style>
</style>
<table class="tb">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Denice</td>
<td>Hobermann</td>
<td>Canada</td>
</tr>
<tr>
<td>Paulo</td>
<td>Cornell</td>
<td>Brazil</td>
</tr>
<tr>
<td>Jane</td>
<td>Hollander</td>
<td>USA</td>
</tr>
</tbody>
</table>
Property List
CSS supports more than 200 CSS properties. Here's a complete list.
Click a name for details.
PROPERTY DESCRIPTION
align-content Aligns items in a flex container along flex
lines.
align-items Aligns evenly spaced items in a flex
container.
align-self Aligns an item inside a flex container.
Vendor Prefixes
Browser vendors regularly experiment with new, non-standard CSS
properties. To indicate that these are browser specific they are prefixed,
like so:
-webkit-...
-moz-...
-ms-...
-o-...
Color Names
In CSS, a color can be specified by using a color name:
Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Example
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.
Example
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>
Hello World
Hello World
Hello World
Example
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>
The following three <div> elements have their background color set with
RGB, HEX, and HSL values:
#ff6347
Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>
This means that there are 256 x 256 x 256 = 16777216 possible colors!
To display black, set all color parameters to 0, like this: rgb(0, 0, 0).
To display white, set all color parameters to 255, like this: rgb(255, 255,
255).
Shades of Gray
Shades of gray are often defined using equal values for all three
parameters:
#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values
between 00 and ff (same as decimal 0-255).
To display black, set all color parameters to 00, like this: #000000.
To display white, set all color parameters to ff, like this: #ffffff.
<h1 style="background-color:#ff0000;">#ff0000</h1>
<h1 style="background-color:#0000ff;">#0000ff</h1>
<h1 style="background-color:#3cb371;">#3cb371</h1>
<h1 style="background-color:#ee82ee;">#ee82ee</h1>
<h1 style="background-color:#ffa500;">#ffa500</h1>
<h1 style="background-color:#6a5acd;">#6a5acd</h1>
Shades of Gray
Shades of gray are often defined using equal values for all three
parameters:
<h1 style="background-color:#404040;">#404040</h1>
<h1 style="background-color:#686868;">#686868</h1>
<h1 style="background-color:#a0a0a0;">#a0a0a0</h1>
<h1 style="background-color:#bebebe;">#bebebe</h1>
<h1 style="background-color:#dcdcdc;">#dcdcdc</h1>
<h1 style="background-color:#f8f8f8;">#f8f8f8</h1>
Saturation
Saturation can be described as the intensity of a color.
50% is 50% gray, but you can still see the color.
Lightness
The lightness of a color can be described as how much light you want to
give the color, where 0% means no light (black), 50% means 50% light
(neither dark nor light), and 100% means full lightness (white).
Example
Shades of Gray
Shades of gray are often defined by setting the hue and saturation to 0,
and adjusting the lightness from 0% to 100% to get darker/lighter
shades:
Example
<h1 style="background-color:hsl(0, 0%, 20%);">hsl(0, 0%, 20%)</h1>
<h1 style="background-color:hsl(0, 0%, 30%);">hsl(0, 0%, 30%)</h1>
<h1 style="background-color:hsl(0, 0%, 40%);">hsl(0, 0%, 40%)</h1>
<h1 style="background-color:hsl(0, 0%, 60%);">hsl(0, 0%, 60%)</h1>
<h1 style="background-color:hsl(0, 0%, 70%);">hsl(0, 0%, 70%)</h1>
<h1 style="background-color:hsl(0, 0%, 90%);">hsl(0, 0%, 90%)</h1>
background-color
background-image
background-repeat
background-attachment
background-position
background (shorthand property)
CSS background-color
The background-color property specifies the background color of an
element.
Example
The background color of a page is set like this:
body {
background-color: lightblue;
}
Other Elements
You can set the background color for any HTML elements:
Example
Here, the <h1>, <p>, and <div> elements will have different background
colors:
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
Opacity / Transparency
The opacity property specifies the opacity/transparency of an element. It
can take a value from 0.0 - 1.0. The lower value, the more transparent:
Example
div {
background-color: green;
opacity: 0.3;
}
You learned from our CSS Colors Chapter, that you can use RGB as a
color value. In addition to RGB, you can use an RGB color value with
an alpha channel (RGBA) - which specifies the opacity for a color.
Example
body {
background-image: url("paper.gif");
}
Example
This example shows a bad combination of text and background image.
The text is hardly readable:
body {
background-image: url("bgdesert.jpg");
}
Note: When using a background image, use an image that does not disturb the
text.
The background image can also be set for specific elements, like the <p>
element:
Example
p {
background-image: url("paper.gif");
}
Example
body {
background-image: url("gradient_bg.png");
}
Example
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
Example
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
In the example above, the background image is placed in the same place
as the text. We want to change the position of the image, so that it does
not disturb the text too much.
CSS background-position
The background-position property is used to specify the position of the
background image.
Example
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Example
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
Example
Specify that the background image should scroll with the rest of the page:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}
CSS Background
17(iv)
Shorthand
CSS background - Shorthand property
To shorten the code, it is also possible to specify all the background
properties in one single property. This is called a shorthand property.
Instead of writing:
body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Example
Use the shorthand property to set the background properties in one
declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
When using the shorthand property the order of the property values is:
background-color
background-image
background-repeat
background-attachment
background-position
It does not matter if one of the property values is missing, as long as the
other ones are in this order. Note that we do not use the background-
attachment property in the examples above, as it does not have a value.
Exercise:
Set the background color of the <h1> element to "lightblue".
<style>
h1 {
: lightblue;
</style>
<body>
<h1>This is a heading</h1>
<p>This is a heading</p>
<p>This is a heading</p>
</body>
*Week 3:*
**Week 3-4: Structuring Content**
HTML Lists
HTML lists allow web developers to group a set of related items
in lists.
Example
Item
Item
Item
Item
1. First item
2. Second item
3. Third item
4. Fourth item
The list items will be marked with bullets (small black circles) by default:
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term:
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
The list items will be marked with bullets (small black circles) by default:
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Value Description
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Circle
<ul style="list-style-type:circle;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Square
<ul style="list-style-type:square;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - None
<ul style="list-style-type:none;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
Note: A list item (<li>) can contain a new list, and other HTML elements,
like images and links, etc.
Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}
li a:hover {
background-color: #111111;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
Chapter Summary
Use the HTML <ul> element to define an unordered list
Use the CSS list-style-type property to define the list item marker
Use the HTML <li> element to define a list item
Lists can be nested
List items can contain other HTML elements
Use the CSS property float:left to display a list horizontally
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Type Description
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Example
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Example
<ol>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea</li>
</ol>
</li>
<li>Milk</li>
</ol>
Note: A list item (<li>) can contain a new list, and other HTML elements,
like images and links, etc.
Chapter Summary
Use the HTML <ol> element to define an ordered list
Use the HTML type attribute to define the numbering type
Use the HTML <li> element to define a list item
Lists can be nested
List items can contain other HTML elements
The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term:
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Chapter Summary
Use the HTML <dl> element to define a description list
Use the HTML <dt> element to define the description term
Use the HTML <dd> element to describe the term in a description list
HTML Exercises
Exercise:
Add a list item with the text "Coffee" inside the <ul> element.
HTML Tables
HTML tables allow web developers to arrange data into rows and
columns.
Example
Example
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
Table Cells
Each table cell is defined by a <td> and a </td> tag.
Everything between <td> and </td> are the content of the table cell.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
Note: A table cell can contain all sorts of HTML elements: text, images,
lists, links, other tables, etc.
Table Rows
Each table row starts with a <tr> and ends with a </tr> tag.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
You can have as many rows as you like in a table; just make sure that
the number of cells are the same in each row.
Note: There are times when a row can have less or more cells than another.
You will learn about that in a later chapter.
Table Headers
Sometimes you want your cells to be table header cells. In those cases
use the <th> tag instead of the <td> tag:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
By default, the text in <th> elements are bold and centered, but you can
change that with CSS.
Exercise:
Add a table row with two table headers.
The two table headers should have the value "Name" and "Age".
<table>
<tr>
<td>Jill Smith</td>
<td>50</td>
</tr>
</table>
HTML Table Tags
Tag Description
Example
table, th, td {
border: 1px solid black;
}
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
Example
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}
Example
table, th, td {
border: 1px solid black;
border-radius: 10px;
}
Skip the border around the table by leaving out table from the css
selector:
Example
th, td {
border: 1px solid black;
border-radius: 10px;
}
dotted
dashed
solid
double
groove
ridge
inset
outset
none
hidden
Example
th, td {
border-style: dotted;
}
Border Color
With the border-color property, you can set the color of the border.
Example
th, td {
border-color: #96D4D4;
}
Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Note: Using a percentage as the size unit for a width means how wide will
this element be compared to its parent element, which in this case is
the <body> element.
Example
<table style="width:100%">
<tr>
<th style="width:70%">Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Example
Exercise:
Use CSS styles to make the table 300 pixels wide.
<table >
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>
Example
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Example
<table>
<tr>
<th>Firstname</th>
<td>Jill</td>
<td>Eve</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
<td>Jackson</td>
</tr>
<tr>
<th>Age</th>
<td>94</td>
<td>50</td>
</tr>
</table>
Example
th {
text-align: left;
}
Name Age
Jill Smith 50
Eve Jackson 94
Example
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Table Caption
You can add a caption that serves as a heading for the entire table.
Monthly savings
Month Savings
January $100
February $50
<style>
table, th, td {
border-collapse: collapse;
th, td {
padding: 5px;
text-align: left;
</style>
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>
Exercise:
Add a table caption that says "Names".
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>
HTML Table Padding &
Spacing
HTML tables can adjust the padding inside the cells, and also
the space between the cells.
With Padding
hello hello hello
With Spacing
hello hello hello
hello hello hello
hello hello hello
Example
th, td {
padding: 15px;
}
To add padding only above the content, use the padding-top property.
And the others sides with the padding-bottom, padding-left,
and padding-right properties:
Example
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}
To change the space between table cells, use the CSS border-
spacing property on the table element:
Example
table {
border-spacing: 30px;
}
Example
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>
Note: The value of the colspan attribute represents the number of columns to
span.
Example
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
Note: The value of the rowspan attribute represents the number of rows
to span.
Exercise:
Use the correct HTML attribute to make the first TH element span two
columns.
<table>
<tr>
<th >Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Example
tr:nth-child(even) {
background-color: #D6EEEE;
}
Note: If you use (odd) instead of (even), the styling will occur on row 1,3,5 etc.
instead of 2,4,6 etc.
Example
td:nth-child(even), th:nth-child(even) {
background-color: #D6EEEE;
}
Note: Put the :nth-child() selector on both th and td elements if you
want to have the styling on both headers and regular table cells.
Combine Vertical and Horizontal Zebra
Stripes
You can combine the styling from the two examples above and you will
have stripes on every other row and every other column.
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
tr:nth-child(even) {
background-color: rgba(150, 212, 212, 0.4);
}
th:nth-child(even),td:nth-child(even) {
background-color: rgba(150, 212, 212, 0.4);
}
<h2>Striped Table</h2>
<p>For zebra-striped tables, use the nth-child() selector and add a
background-color to all even (or odd) table rows:</p>
<table style="width:100%">
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
<th>FRI</th>
<th>SAT</th>
<th>SUN</th>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
Horizontal Dividers
First Name Last Name Savings
First Name Last Name Savings
If you specify borders only at the bottom of each table row, you will have
a table with horizontal dividers.
Example
<style>
table {
border-collapse: collapse;
width: 100%;
}
tr {
border-bottom: 1px solid #ddd;
}
</style>
</head>
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Savings</th>
</tr>
<tr>
<td>Peter</td>
<td>Griffin</td>
<td>$100</td>
</tr>
<tr>
<td>Lois</td>
<td>Griffin</td>
<td>$150</td>
</tr>
<tr>
<td>Joe</td>
<td>Swanson</td>
<td>$300</td>
</tr>
<tr>
<td>Cleveland</td>
<td>Brown</td>
<td>$250</td>
</tr>
</table>
Hoverable Table
Use the :hover selector on tr to highlight table rows on mouse over:
The span attribute specifies how many columns that get the style.
Note: There is a very limited selection of legal CSS properties for colgroups.
Example
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<h2>Colgroup</h2>
<p>Add the a colgroup with a col element that spans over two
columns to define a style for the two columns:</p>
Note: The <colgroup> tag must be a child of a <table> element and should be
placed before any other table elements, like <thead>, <tr>, <td> etc., but after
the <caption> element, if present.
<style>
table, th, td {
border-collapse: collapse;
</style>
</head>
<body>
<colgroup>
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
<th>FRI</th>
<th>SAT</th>
<th>SUN</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
<tr>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
</tr>
</table>
Empty Colgroups
If you want to style columns in the middle of a table, insert a
"empty" <col> element (with no styles) for the columns before:
Example
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
</style>
</head>
<body>
<h2>Empty Colgroups</h2>
<p>Add "empty" col elements that represents the columns before the
columns you want to style:</p>
<colgroup>
<col span="3">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
<th>FRI</th>
<th>SAT</th>
<th>SUN</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
<tr>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
</tr>
</table>
Hide Columns
You can hide columns with the visibility: collapse property:
<style>
table, th, td {
border-collapse: collapse;
</style>
</head>
<body>
<h2>Hide Columns</h2>
<colgroup>
<col span="2">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
<th>FRI</th>
<th>SAT</th>
<th>SUN</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
<tr>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
</tr>
</table>
<p><b>Note:</b> The table columns does not collapse properly in
Safari browsers.</p>
</body>
Block-level Elements
A block-level element always starts on a new line, and the browsers
automatically add some space (a margin) before and after the element.
Example
<p>Hello World</p>
<div>Hello World</div>
<address>
<article>
<aside>
<blockquote>
<canvas>
<dd>
<div>
<dl>
<dt>
<fieldset>
<figcaption>
<figure>
<footer>
<form>
<h1>-<h6>
<header>
<hr>
<li>
<main>
<nav>
<noscript>
<ol>
<p>
<pre>
<section>
<table>
<tfoot>
<ul>
<video>
Inline Elements
An inline element does not start on a new line.
Example
<span>Hello World</span>
<a>
<abbr>
<acronym>
<b>
<bdo>
<big>
<br>
<button>
<cite>
<code>
<dfn>
<em>
<i>
<img>
<input>
<kbd>
<label>
<map>
<object>
<output>
<q>
<samp>
<script>
<select>
<small>
<span>
<strong>
<sub>
<sup>
<textarea>
<time>
<tt>
<var>
The <div> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <div> element can be used to style
blocks of content:
Example
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous
city in the United Kingdom, with a metropolitan area of over 13
million inhabitants.</p>
</div>
When used together with CSS, the <span> element can be used to style
parts of the text:
Example
Chapter Summary
There are two display values: block and inline
A block-level element always starts on a new line and takes up the
full width available
An inline element does not start on a new line and it only takes up
as much width as necessary
The <div> element is a block-level and is often used as a container
for other HTML elements
The <span> element is an inline container used to mark up a part of
a text, or a part of a document
HTML Tags
Tag Description
The CSS box model is essentially a box that wraps around every HTML
element. It consists of: margins, borders, padding, and the actual
content. The image below illustrates the box model:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is
transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is
transparent
The box model allows us to add a border around elements, and to define
space between elements.
Example
Demonstration of the box model:
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
Width and Height of an Element
In order to set the width and height of an element correctly in all
browsers, you need to know how the box model works.
Important: When you set the width and height properties of an element with
CSS, you just set the width and height of the content area. To calculate the
full size of an element, you must also add padding, borders and margins.
Example
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
Total element width = width + left padding + right padding + left border
+ right border + left margin + right margin
Exercise:
Set the width of the <div> element to "200px".
<style> {
: ;
}
</style>
<body>
<div>
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
</div>
</body>
Header
Navigation Menu
Content
Main Content
Content
Footer
There are tons of different layout designs to choose from. However, the
structure above, is one of the most common, and we will take a closer
look at it in this tutorial.
Header
A header is usually located at the top of the website (or right below a top
navigation menu). It often contains a logo or the website name:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body {
margin: 0;
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
</body>
</html>
Navigation Bar
A navigation bar contains a list of links to help visitors navigating through
your website:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
* {
box-sizing: border-box;
body {
margin: 0;
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}
.topnav {
overflow: hidden;
background-color: #333;
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
text-decoration: none;
.topnav a:hover {
background-color: #ddd;
color: black;
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
</body>
</html>
Content
The layout in this section, often depends on the target users. The most
common layout is one (or combining them) of the following:
1-column:
2-column:
3-column:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Website Layout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
*{
box-sizing: border-box;
}
body {
margin: 0;
}
/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width:600px) {
.column {
width: 100%;
}
}
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
<p>Resize the browser window to see the responsive effect.</p>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
<div class="row">
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis
velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo
tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis
velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo
tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis
velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo
tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
</div>
</body>
</html>
Unequal Columns
The main content is the biggest and the most important part of your site.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
* {
box-sizing: border-box;
body {
margin: 0;
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
.topnav {
overflow: hidden;
background-color: #333;
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
text-decoration: none;
.topnav a:hover {
background-color: #ddd;
color: black;
.column {
float: left;
padding: 10px;
}
/* Left and right column */
.column.side {
width: 25%;
/* Middle column */
.column.middle {
width: 50%;
.row::after {
content: "";
display: table;
clear: both;
.column.side, .column.middle {
width: 100%;
.footer {
background-color: #f1f1f1;
padding: 10px;
text-align: center;
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
<div class="row">
<h2>Side</h2>
</div>
<h2>Main Content</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque
ultricies, eget elementum magna tristique. Quisque vehicula, risus
eget aliquam placerat, purus leo tincidunt eros, eget luctus quam
orci in velit. Praesent scelerisque tortor sed accumsan
convallis.</p>
</div>
<h2>Side</h2>
</div>
</div>
</body>
</html>
Footer
The footer is placed at the bottom of your page. It often contains
information like copyright and contact info:
Example
<div class="footer">
<p>Footer</p>
</div>
Responsive Website Layout
By using some of the CSS code above, we have created a responsive
website layout, which varies between two columns and full-width columns
depending on screen width:
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
body {
font-family: Arial;
padding: 10px;
background: #f1f1f1;
/* Header/Blog Title */
.header {
padding: 30px;
text-align: center;
background: white;
.header h1 {
font-size: 50px;
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
text-decoration: none;
.topnav a:hover {
background-color: #ddd;
color: black;
/* Left column */
.leftcolumn {
float: left;
width: 75%;
/* Right column */
.rightcolumn {
float: left;
width: 25%;
background-color: #f1f1f1;
padding-left: 20px;
}
/* Fake image */
.fakeimg {
background-color: #aaa;
width: 100%;
padding: 20px;
.card {
background-color: white;
padding: 20px;
margin-top: 20px;
.row::after {
content: "";
display: table;
clear: both;
/* Footer */
.footer {
padding: 20px;
text-align: center;
background: #ddd;
margin-top: 20px;
}
/* Responsive layout - when the screen is less than 800px wide, make the two
columns stack on top of each other instead of next to each other */
.leftcolumn, .rightcolumn {
width: 100%;
padding: 0;
/* Responsive layout - when the screen is less than 400px wide, make the
navigation links stack on top of each other instead of next to each other */
.topnav a {
float: none;
width: 100%;
</style>
</head>
<body>
<div class="header">
<h1>My Website</h1>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<div class="row">
<div class="leftcolumn">
<div class="card">
<h2>TITLE HEADING</h2>
<p>Some text..</p>
</div>
<div class="card">
<h2>TITLE HEADING</h2>
<p>Some text..</p>
</div>
</div>
<div class="rightcolumn">
<div class="card">
<h2>About Me</h2>
</div>
<div class="card">
<h3>Popular Post</h3>
<div class="fakeimg"><p>Image</p></div>
<div class="fakeimg"><p>Image</p></div>
<div class="fakeimg"><p>Image</p></div>
</div>
<div class="card">
<h3>Follow Me</h3>
<p>Some text..</p>
</div>
</div>
</div>
<div class="footer">
<h2>Footer</h2>
</div>
</body>
</html>
static
relative
fixed
absolute
sticky
Elements are then positioned using the top, bottom, left, and right
properties. However, these properties will not work unless
the position property is set first. They also work differently depending on
the position value.
position: static;
HTML elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, and
right properties.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div.static {
position: static;
</style>
</head>
<body>
<h2>position: static;</h2>
<div class="static">
</div>
</body>
</html>
position: relative;
An element with position: relative; is positioned relative to its normal
position.
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
left: 30px;
</style>
</head>
<body>
<h2>position: relative;</h2>
<div class="relative">
</div>
</body>
</html>
position: fixed;
An element with position: fixed; is positioned relative to the viewport,
which means it always stays in the same place even if the page is
scrolled. The top, right, bottom, and left properties are used to position
the element.
A fixed element does not leave a gap in the page where it would normally
have been located.
Notice the fixed element in the lower-right corner of the page. Here is the
CSS that is used:
<!DOCTYPE html>
<html>
<head>
<style>
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
</style>
</head>
<body>
<h2>position: fixed;</h2>
<div class="fixed">
</div>
</body>
</html>
position: absolute;
An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like
fixed).
Note: Absolute positioned elements are removed from the normal flow,
and can overlap elements.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 400px;
height: 200px;
div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
</style>
</head>
<body>
<h2>position: absolute;</h2>
</div>
</body>
</html>
position: sticky;
An element with position: sticky; is positioned based on the user's
scroll position.
Note: Internet Explorer does not support sticky positioning. Safari requires a -
webkit- prefix (see example below). You must also specify at least one
of top, right, bottom or left for sticky positioning to work.
In this example, the sticky element sticks to the top of the page (top: 0),
when you reach its scroll position.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
padding: 5px;
background-color: #cae8ca;
</style>
</head>
<body>
<div style="padding-bottom:2000px">
<p>In this example, the sticky element sticks to the top of the
page (top: 0), when you reach its scroll position.</p>
</div>
</body>
</html>
Top-Left
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
.topleft {
position: absolute;
top: 8px;
left: 16px;
font-size: 18px;
img {
width: 100%;
height: auto;
opacity: 0.3;
</style>
</head>
<body>
<h2>Image Text</h2>
<div class="container">
</div>
</body>
</html>
TOP-RIGHT
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
.topright {
position: absolute;
top: 8px;
right: 16px;
font-size: 18px;
img {
width: 100%;
height: auto;
opacity: 0.3;
}
</style>
</head>
<body>
<h2>Image Text</h2>
<div class="container">
</div>
</body>
</html>
BOTTOM-LEFT
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
.bottomleft {
position: absolute;
bottom: 8px;
left: 16px;
font-size: 18px;
img {
width: 100%;
height: auto;
opacity: 0.3;
</style>
</head>
<body>
<h2>Image Text</h2>
<div class="container">
</div>
</body>
</html>
BOTTOM-RIGHT
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
.bottomright {
position: absolute;
bottom: 8px;
right: 16px;
font-size: 18px;
img {
width: 100%;
height: auto;
opacity: 0.3;
</style>
</head>
<body>
<h2>Image Text</h2>
<div class="container">
</div>
</body>
</html>
CENTERED
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
.center {
position: absolute;
top: 50%;
width: 100%;
text-align: center;
font-size: 18px;
img {
width: 100%;
height: auto;
opacity: 0.3;
</style>
</head>
<body>
<h2>Image Text</h2>
<div class="container">
<div class="center">Centered</div>
</div>
</body>
</html>
Exercise:
Position the <h1> element to always be 50px from the top, and 10px
from the right, relative to the window/frame edges.
<style>
h1 {
: ;
: 50px;
: 10px;
}
</style>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</body>
*Week 4:*
Example
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
</body>
</html>
Example
Create a class named "city":
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
</head>
<body>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</body>
</html>
Multiple Classes
HTML elements can belong to more than one class.
To define multiple classes, separate the class names with a space, e.g.
<div class="city main">. The element will be styled according to all the
classes specified.
In the following example, both <h2> and <p> point to the "city" class and
will share the same style:
Example
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
Example
Click on a button to hide all elements with the class name "city":
<!DOCTYPE html>
<html>
<body>
<h2 class="city">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
x[i].style.display = "none";
</script>
</body>
</html>
Don't worry if you don't understand the code in the example above.
You will learn more about JavaScript in coming lessons
Chapter Summary
The HTML class attribute specifies one or more class names for an
element
Classes are used by CSS and JavaScript to select and access specific
elements
The class attribute can be used on any HTML element
The class name is case sensitive
Different HTML elements can point to the same class name
JavaScript can access elements with a specific class name with
the getElementsByClassName() method
Exercise:
Create a class selector named "special".
Add a color property with the value "blue" inside the "special" class.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
</body>
</html>
HTML id Attribute
The HTML id attribute is used to specify a unique id for an HTML
element.
You cannot have more than one element with the same id in an
HTML document.
The syntax for id is: write a hash character (#), followed by an id name.
Then, define the CSS properties within curly braces {}.
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<head>
<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<h2>Using The id Attribute in JavaScript</h2>
<p>JavaScript can access an element with a specified id by using
the getElementById() method:</p>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice
day!";
}
</script>
</body>
</html>
Chapter Summary
The id attribute is used to specify a unique id for an HTML element
The value of the id attribute must be unique within the HTML
document
The id attribute is used by CSS and JavaScript to style/select a
specific element
The value of the id attribute is case sensitive
The id attribute is also used to create HTML bookmarks
JavaScript can access an element with a specific id with
the getElementById() method
Exercise:
Add the correct HTML attribute to make the H1 element red.
<!DOCTYPE html>
<html>
<head>
<style>
#myheader {color:red;}
</style>
</head>
<body>
</body>
</html>
HTML Semantic
Elements
Semantic elements = elements with a meaning.
In HTML there are some semantic elements that can be used to define
different parts of a web page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
HTML <section> Element
The <section> element defines a section in a document.
Chapters
Introduction
News items
Contact information
A web page could normally be split into sections for introduction, content,
and contact information.
Example
<!DOCTYPE html>
<html>
<body>
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is an international organization working on
issues regarding the conservation, research and restoration of the environment, formerly
named the World Wildlife Fund. WWF was founded in 1961.</p>
</section>
<section>
<p>The Panda has become the symbol of WWF. The well-known panda logo of WWF
originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the
London Zoo in the same year of the establishment of WWF.</p>
</section>
</body>
</html>
Forum posts
Blog posts
User comments
Product cards
Newspaper articles
Example
<!DOCTYPE html>
<html>
<head>
<style>
.all-browsers {
margin: 0;
padding: 5px;
background-color: lightgray;
}
.browser {
background: white;
}
<article class="all-browsers">
<h1>Most Popular Browsers</h1>
<article class="browser">
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google, released
in 2008. Chrome is the world's most popular web browser today!</p>
</article>
<article class="browser">
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by
Mozilla. Firefox has been the second most popular web browser since
January, 2018.</p>
</article>
<article class="browser">
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft,
released in 2015. Microsoft Edge replaced Internet Explorer.</p>
</article>
</article>
</body>
</html>
Can we use the definitions to decide how to nest those elements? No, we
cannot!
Note: You can have several <header> elements in one HTML document.
However, <header> cannot be placed within a <footer>, <address> or
another <header> element.
Example
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural
environment,
and build a future in which humans live in harmony with nature.</p>
</article>
authorship information
copyright information
contact information
sitemap
back to top links
related documents
<footer>
<p>Author: Hege Refsnes</p>
<p><a href="mailto:[email protected]">[email protected]</a></p>
</footer>
Notice that NOT all links of a document should be inside a <nav> element.
The <nav> element is intended only for major blocks of navigation links.
Browsers, such as screen readers for disabled users, can use this element to
determine whether to omit the initial rendering of this content.
Example
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
Example
Display some content aside from the content it is placed in with css styling:
<html>
<head>
<style>
aside {
width: 30%;
padding-left: 15px;
margin-left: 15px;
float: right;
font-style: italic;
background-color: lightgray;
}
</style>
</head>
<body>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<aside>
<p>The Epcot center is a theme park at Walt Disney World Resort
featuring exciting attractions, international pavilions, award-
winning fireworks and seasonal special events.</p>
</aside>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
</body>
</html>
HTML <figure> and <figcaption>
Elements
The <figure> tag specifies self-contained content, like illustrations,
diagrams, photos, code listings, etc.
<figure>
<img src="pic_trulli.jpg" alt="Trulli">
<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>
</figure>
Tag Description
<details> Defines additional details that the user can view or hide
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<style>
*{
box-sizing: border-box;
body {
header {
background-color: #666;
padding: 30px;
text-align: center;
font-size: 35px;
color: white;
nav {
float: left;
width: 30%;
background: #ccc;
padding: 20px;
nav ul {
list-style-type: none;
padding: 0;
article {
float: left;
padding: 20px;
width: 70%;
background-color: #f1f1f1;
}
/* Clear floats after the columns */
section::after {
content: "";
display: table;
clear: both;
footer {
background-color: #777;
padding: 10px;
text-align: center;
color: white;
/* Responsive layout - makes the two columns/boxes stack on top of each other instead of
next to each other, on small screens */
nav, article {
width: 100%;
height: auto;
</style>
</head>
<body>
<p>In this example, we have created a header, two columns/boxes and a footer. On smaller
screens, the columns will stack on top of each other.</p>
<p>Resize the browser window to see the responsive effect (you will learn more about this in
our next chapter - HTML Responsive.)</p>
<header>
<h2>Cities</h2>
</header>
<section>
<nav>
<ul>
<li><a href="#">London</a></li>
<li><a href="#">Paris</a></li>
<li><a href="#">Tokyo</a></li>
</ul>
</nav>
<article>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United
Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.</p>
</article>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
CSS framework
CSS float property
CSS flexbox
CSS grid
CSS Frameworks
If you want to create your layout fast, you can use a CSS framework,
like W3.CSS or Bootstrap or Tailwind CSS
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<style>
*{
box-sizing: border-box;
body {
header {
background-color: #666;
padding: 30px;
text-align: center;
font-size: 35px;
color: white;
nav {
float: left;
width: 30%;
background: #ccc;
padding: 20px;
}
/* Style the list inside the menu */
nav ul {
list-style-type: none;
padding: 0;
article {
float: left;
padding: 20px;
width: 70%;
background-color: #f1f1f1;
section::after {
content: "";
display: table;
clear: both;
footer {
background-color: #777;
padding: 10px;
text-align: center;
color: white;
}
/* Responsive layout - makes the two columns/boxes stack on top of each other instead of
next to each other, on small screens */
nav, article {
width: 100%;
height: auto;
</style>
</head>
<body>
<p>In this example, we have created a header, two columns/boxes and a footer. On smaller
screens, the columns will stack on top of each other.</p>
<p>Resize the browser window to see the responsive effect (you will learn more about this in
our next chapter - HTML Responsive.)</p>
<header>
<h2>Cities</h2>
</header>
<section>
<nav>
<ul>
<li><a href="#">London</a></li>
<li><a href="#">Paris</a></li>
<li><a href="#">Tokyo</a></li>
</ul>
</nav>
<article>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United
Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.</p>
</article>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<style>
*{
box-sizing: border-box;
body {
}
/* Style the header */
header {
background-color: #666;
padding: 30px;
text-align: center;
font-size: 35px;
color: white;
section {
display: -webkit-flex;
display: flex;
nav {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
background: #ccc;
padding: 20px;
nav ul {
list-style-type: none;
padding: 0;
}
/* Style the content */
article {
-webkit-flex: 3;
-ms-flex: 3;
flex: 3;
background-color: #f1f1f1;
padding: 10px;
footer {
background-color: #777;
padding: 10px;
text-align: center;
color: white;
/* Responsive layout - makes the menu and the content (inside the section) sit on top of
each other instead of next to each other */
section {
-webkit-flex-direction: column;
flex-direction: column;
</style>
</head>
<body>
<h2>CSS Layout Flexbox</h2>
<p>In this example, we have created a header, two columns/boxes and a footer. On smaller
screens, the columns will stack on top of each other.</p>
<header>
<h2>Cities</h2>
</header>
<section>
<nav>
<ul>
<li><a href="#">London</a></li>
<li><a href="#">Paris</a></li>
<li><a href="#">Tokyo</a></li>
</ul>
</nav>
<article>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United
Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.</p>
</article>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
Example
This will set the viewport of your page, which will give the browser
instructions on how to control the page's dimensions and scaling.
Responsive Images
Responsive images are images that scale nicely to fit any browser size.
Resize the browser window to see how the image below changes
depending on the width:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Show Different Images Depending on Browser Width</h2>
<p>Resize the browser width and the image will change at 600px and
1500px.</p>
<picture>
<source srcset="flowers.jpg">
</picture>
</body>
</html>
That way the text size will follow the size of the browser window:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Media Queries
In addition to resize text and images, it is also common to use media
queries in responsive web pages.
With media queries you can define completely different styles for
different browser sizes.
Example: resize the browser window to see that the three div elements
below will display horizontally on large screens and stack vertically on
small screens:
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
.left {
background-color: #2196F3;
padding: 20px;
float: left;
width: 20%; /* The width is 20%, by default */
.main {
background-color: #f1f1f1;
padding: 20px;
float: left;
.right {
background-color: #04AA6D;
padding: 20px;
float: left;
</style>
</head>
<body>
<h2>Media Queries</h2>
<p>Make sure you reach the breakpoint at 800px when resizing this
frame.</p>
<div class="left">
<p>Left Menu</p>
</div>
<div class="main">
<p>Main Content</p>
</div>
<div class="right">
<p>Right Content</p>
</div>
</body>
</html>
<html>
<head>
<style>
* {
box-sizing: border-box;
.menu {
float: left;
width: 20%;
text-align: center;
.menu a {
background-color: #e5e5e5;
padding: 8px;
margin-top: 7px;
display: block;
width: 100%;
color: black;
.main {
float: left;
width: 60%;
padding: 0 20px;
.right {
background-color: #e5e5e5;
float: left;
width: 20%;
padding: 15px;
margin-top: 7px;
text-align: center;
width: 100%;
}
</style>
</head>
<body style="font-family:Verdana;color:#aaaaaa;">
<div style="background-color:#e5e5e5;padding:15px;text-align:center;">
<h1>Hello World</h1>
</div>
<div style="overflow:auto">
<div class="menu">
</div>
<div class="main">
<h2>Lorum Ipsum</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</div>
<div class="right">
<h2>About</h2>
</div>
</div>
<div style="background-color:#e5e5e5;text-align:center;padding:10px;margin-top:7px;">©
copyright w3schools.com</div>
</body>
</html>
CSS Flexbox
CSS3 Flexbox
Flexible boxes, or flexbox, is a new layout mode in CSS3.
Use of flexbox ensures that elements behave predictably when the page
layout must accommodate different screen sizes and different display
devices.
Flex items are positioned inside a flex container along a flex line. By
default there is only one flex line per flex container.
The following example shows three flex items. They are positioned by
default: along the horizontal flex line, from left to right:
<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>
flex-direction
flex-wrap
flex-flow
justify-content
align-items
align-content
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
Flex Direction
The flex-direction property specifies the direction of the flexible items
inside the flex container. The default value of flex-direction is row (left-
to-right, top-to-bottom).
The following example shows the result of using the row-reverse value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row-reverse;
flex-direction: row-reverse;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the column value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column-reverse;
flex-direction: column-reverse;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the flex-end value:
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: flex-end;
justify-content: flex-end;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the center value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the space-between value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: space-between;
justify-content: space-between;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the space-around value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-justify-content: space-around;
justify-content: space-around;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the stretch value (this is
the default value):
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: stretch;
align-items: stretch;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the flex-start value:
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: flex-start;
align-items: flex-start;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the flex-end value:
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: flex-end;
align-items: flex-end;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the center value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the baseline value:
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-align-items: baseline;
align-items: baseline;
width: 400px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the nowrap value (this is
the default value):
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: nowrap;
flex-wrap: nowrap;
width: 300px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the wrap value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
width: 300px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the wrap-reverse value:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap-reverse;
flex-wrap: wrap-reverse;
width: 300px;
height: 250px;
background-color: lightgrey;
}
The following example shows the result of using the center value:
Example
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-align-content: center;
align-content: center;
width: 300px;
height: 300px;
background-color: lightgrey;
}
Example
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
.first {
-webkit-order: -1;
order: -1;
}
Margin
Setting margin: auto; will absorb extra space. It can be used to push flex
items into different positions.
In the following example we set margin-right: auto; on the first flex item.
This will cause all the extra space to be absorbed to the right of that
element:
Example
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: 10px;
}
.flex-item:first-child {
margin-right: auto;
}
Perfect Centering
In the following example we will solve an almost daily problem: perfect
centering.
It is very easy with flexbox. Setting margin: auto; will make the item
perfectly centered in both axis:
Example
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: auto;
}
align-self
The align-self property of flex items overrides the flex container's align-
items property for that item. It has the same possible values as
the align-items property.
The following example sets different align-self values to each flex item:
Example
.flex-item {
background-color: cornflowerblue;
width: 60px;
min-height: 100px;
margin: 10px;
}
.item1 {
-webkit-align-self: flex-start;
align-self: flex-start;
}
.item2 {
-webkit-align-self: flex-end;
align-self: flex-end;
}
.item3 {
-webkit-align-self: center;
align-self: center;
}
.item4 {
-webkit-align-self: baseline;
align-self: baseline;
}
.item5 {
-webkit-align-self: stretch;
align-self: stretch;
}
flex
The flex property specifies the length of the flex item, relative to the rest
of the flex items inside the same container.
In the following example, the first flex item will consume 2/4 of the free
space, and the other two flex items will consume 1/4 of the free space
each:
Example
.flex-item {
background-color: cornflowerblue;
margin: 10px;
}
.item1 {
-webkit-flex: 2;
flex: 2;
}
.item2 {
-webkit-flex: 1;
flex: 1;
}
.item3 {
-webkit-flex: 1;
flex: 1;
}
<html>
<head>
<style>
.flex-container {
display: flex;
background-color: #f1f1f1;
background-color: DodgerBlue;
color: white;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
</style>
</head>
<body>
<h1>Flexible Items</h1>
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</body>
</html>
order
flex-grow
flex-shrink
flex-basis
flex
align-self
The first flex item in the code does not have to appear as the first item in
the layout.
Example
The order property can change the order of the flex items:
<div class="flex-container">
<div style="order: 3">1</div>
<div style="order: 2">2</div>
<div style="order: 4">3</div>
<div style="order: 1">4</div>
</div>
Example
Make the third flex item grow eight times faster than the other flex items:
<div class="flex-container">
<div style="flex-grow: 1">1</div>
<div style="flex-grow: 1">2</div>
<div style="flex-grow: 8">3</div>
</div>
Example
Do not let the third flex item shrink as much as the other flex items:
<div class="flex-container">
<div>1</div>
<div>2</div>
<div style="flex-shrink: 0">3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
</div>
Example
Set the initial length of the third flex item to 200 pixels:
<div class="flex-container">
<div>1</div>
<div>2</div>
<div style="flex-basis: 200px">3</div>
<div>4</div>
</div>
Example
Make the third flex item not growable (0), not shrinkable (0), and with an
initial length of 200 pixels:
<div class="flex-container">
<div>1</div>
<div>2</div>
<div style="flex: 0 0 200px">3</div>
<div>4</div>
</div>
Example
Example
Align the second flex item at the top of the container, and the third flex
item at the bottom of the container:
<div class="flex-container">
<div>1</div>
<div style="align-self: flex-start">2</div>
<div style="align-self: flex-end">3</div>
<div>4</div>
</div>
Property Description
flex- Specifies the direction of the flexible items inside a flex container
direction
justify- Horizontally aligns the flex items when the items do not use all availabl
content the main-axis
align- Vertically aligns the flex items when the items do not use all available s
items cross-axis
flex-wrap Specifies whether the flex items should wrap or not, if there is not enou
on one flex line
order Specifies the order of a flexible item relative to the rest of the flex item
container
align-self Used on flex items. Overrides the container's align-items property
flex Specifies the length of a flex item, relative to the rest of the flex items
container
Property Description
align-self Specifies the alignment for a flex item (overrides the flex container's al
flex A shorthand property for the flex-grow, flex-shrink, and the flex-basis p
flex-grow Specifies how much a flex item will grow relative to the rest of the flex
the same container
flex- Specifies how much a flex item will shrink relative to the rest of the flex
shrink the same container
order Specifies the order of the flex items inside the same container
Grid Elements
A grid layout consists of a parent element, with one or more child
elements.
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<h1>Grid Elements</h1>
<p>A Grid Layout must have a parent element with the <em>display</em> property set to
<em>grid</em> or <em>inline-grid</em>.</p>
<p>Direct child element(s) of the grid container automatically becomes grid items.</p>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
</div>
</body>
</html>
Display Property
An HTML element becomes a grid container when its display property is
set to grid or inline-grid.
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: inline-grid;
grid-template-columns: auto auto auto;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<h1>display: inline-grid</h1>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
</div>
</body>
</html>
All direct children of the grid container automatically become grid items.
Grid Columns
The vertical lines of grid items are called columns.
Grid Rows
The horizontal lines of grid items are called rows.
Grid Gaps
The spaces between each column/row are called gaps.
You can adjust the gap size by using one of the following properties:
column-gap
row-gap
gap
Example
The column-gap property sets the gap between the columns:
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
column-gap: 50px;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
padding: 20px;
font-size: 30px;
text-align: center;
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
</div>
</body>
</html>
Example
The gap property is a shorthand property for the row-gap and the column-
gap properties:
The gap property can also be used to set both the row gap and the
column gap in one value:
The gap property can also be used to set both the row gap and the
column gap in one value:
Grid containers consist of grid items, placed inside columns and rows.
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
gap: 10px;
background-color: #2196F3;
padding: 10px;
text-align: center;
font-size: 30px;
</style>
</head>
<body>
<h1>Grid Container</h1>
<p>A Grid Container consists of grid items arranged in columns and
rows</p>
<div class="grid-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
</body>
</html>
If you want your grid layout to contain 4 columns, specify the width of
the 4 columns, or "auto" if all columns should have the same width.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
gap: 10px;
background-color: #2196F3;
padding: 10px;
text-align: center;
padding: 20px 0;
font-size: 30px;
</style>
</head>
<body>
<div class="grid-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
</body>
</html>
Note: If you have more than 4 items in a 4 columns grid, the grid will
automatically add a new row to put the items in.
Example
.grid-container {
display: grid;
grid-template-columns: 80px 200px auto 40px;
}
Example
.grid-container {
display: grid;
grid-template-rows: 80px 200px;
}
Note: The grid's total width has to be less than the container's width for
the justify-content property to have any effect.
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
justify-content: space-evenly;
gap: 10px;
background-color: #2196F3;
padding: 10px;
text-align: center;
padding: 20px 0;
font-size: 30px;
</style>
</head>
<body>
<div class="grid-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
</body>
</html>
.grid-container {
display: grid;
justify-content: space-around;
}
.grid-container {
display: grid;
justify-content: space-between;
}
.grid-container {
display: grid;
justify-content: center;
}
.grid-container {
display: grid;
justify-content: start;
}
.grid-container {
display: grid;
justify-content: end;
}
Note: The grid's total height has to be less than the container's height
for the align-content property to have any effect.
.grid-container {
display: grid;
height: 400px;
align-content: center;
}
.grid-container {
display: grid;
height: 400px;
align-content: space-evenly;
}
.grid-container {
display: grid;
height: 400px;
align-content: space-around;
}
.grid-container {
display: grid;
height: 400px;
align-content: space-between;
}
.grid-container {
display: grid;
height: 400px;
align-content: start;
}
.grid-container {
display: grid;
height: 400px;
align-content: end;
}
By default, a container has one grid item for each column, in each row,
but you can style the grid items so that they will span multiple columns
and/or rows.
You define where the item will start, and where the item will end.
To place an item, you can refer to line numbers, or use the keyword
"span" to define how many columns the item will span.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
grid-template-columns: auto auto auto auto auto auto;
gap: 10px;
background-color: #2196F3;
padding: 10px;
}
.item1 {
grid-column: 1 / 5;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="item1">1</div>
<div class="item2">2</div>
<div class="item3">3</div>
<div class="item4">4</div>
<div class="item5">5</div>
<div class="item6">6</div>
<div class="item7">7</div>
<div class="item8">8</div>
<div class="item9">9</div>
<div class="item10">10</div>
<div class="item11">11</div>
<div class="item12">12</div>
<div class="item13">13</div>
<div class="item14">14</div>
<div class="item15">15</div>
</div>
</body>
</html>
Example
Make "item1" start on column 1 and span 3 columns:
.item1 {
grid-column: 1 / span 3;
}
Example
Make "item2" start on column 2 and span 3 columns:
.item2 {
grid-column: 2 / span 3;
}
You define where the item will start, and where the item will end.
Note: The grid-row property is a shorthand property for the grid-row-start and
the grid-row-end properties.
To place an item, you can refer to line numbers, or use the keyword
"span" to define how many rows the item will span:
Example
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
grid-template-columns: auto auto auto auto auto auto;
gap: 10px;
background-color: #2196F3;
padding: 10px;
}
.item1 {
grid-row: 1 / 4;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="item1">1</div>
<div class="item2">2</div>
<div class="item3">3</div>
<div class="item4">4</div>
<div class="item5">5</div>
<div class="item6">6</div>
<div class="item7">7</div>
<div class="item8">8</div>
<div class="item9">9</div>
<div class="item10">10</div>
<div class="item11">11</div>
<div class="item12">12</div>
<div class="item13">13</div>
<div class="item14">14</div>
<div class="item15">15</div>
<div class="item16">16</div>
</div>
</body>
</html>
Example
Make "item8" start on row-line 1 and column-line 2, and end on row-line
5 and column line 6:
.item8 {
grid-area: 1 / 2 / 5 / 6;
}
Example
Make "item8" start on row-line 2 and column-line 1, and span 2 rows and
3 columns:
.item8 {
grid-area: 2 / 1 / span 2 / span 3;
}
Example
Item1 gets the name "myArea" and spans all five columns in a five columns
grid layout:
.item1 {
grid-area: myArea;
}
.grid-container {
grid-template-areas: 'myArea myArea myArea myArea myArea';
}
Example
Let "myArea" span two columns in a five columns grid layout (period signs
represent items with no name):
.item1 {
grid-area: myArea;
}
.grid-container {
grid-template-areas: 'myArea myArea . . .';
}
To define two rows, define the column of the second row inside another
set of apostrophes:
Example
.grid-container {
grid-template-areas: 'myArea myArea . . .' 'myArea myArea . . .';
}
Example
Name all items, and make a ready-to-use webpage template:
.grid-container {
grid-template-areas:
'header header header header header header'
'menu main main main right right'
'menu footer footer footer footer footer';
}
The first item in the HTML code does not have to appear as the first item in the
grid.
.item1 { grid-area: 1 / 3 / 2 / 4; }
.item2 { grid-area: 2 / 3 / 3 / 4; }
.item3 { grid-area: 1 / 1 / 2 / 2; }
.item4 { grid-area: 1 / 2 / 2 / 3; }
.item5 { grid-area: 2 / 1 / 3 / 2; }
.item6 { grid-area: 2 / 2 / 3 / 3; }
You can re-arrange the order for certain screen sizes, by using media
queries:
Example
HTML Forms
The <form> Element
An HTML form is used to collect user input. The user input is
most often sent to a server for processing.The <form> element
defines an HTML form:
Type Description
Text Fields
The <input type="text"> defines a single-line input field for text input.
Example
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
Note: The form itself is not visible. Also note that the default width of an input
field is 20 characters.
The <label> element also helps users who have difficulty clicking on very
small regions (such as radio buttons or checkboxes) - because when the
user clicks the text within the <label> element, it toggles the radio
button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.
Radio Buttons
The <input type="radio"> defines a radio button.
Example
<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaSc
ript">
<label for="javascript">JavaScript</label>
</form>
Checkboxes
The <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number
of choices.
Example
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
The Name Attribute for <input>
Notice that each input field must have a name attribute to be submitted.
If the name attribute is omitted, the value of the input field will not be
sent at all.
Example
This example will not submit the value of the "First name" input field:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>
Exercise:
In the form below, add an input field with the type "button" and the value
"OK".
<form>
<>
</form>
Usually, the form data is sent to a file on the server when the user clicks
on the submit button.
In the example below, the form data is sent to a file called
"action_page.php". This file contains a server-side script that handles the
form data:
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
Tip: If the action attribute is omitted, the action is set to the current
page.
Value Description
The default value is _self which means that the response will open in the
current window.
Example
Here, the submitted result will open in a new browser tab:
<form action="/action_page.php" target="_blank">
Example
This example uses the GET method when submitting the form data:
Example
This example uses the POST method when submitting the form data:
<form action="/action_page.php" method="post">
Notes on GET:
Notes on POST:
Appends the form data inside the body of the HTTP request (the
submitted form data is not shown in the URL)
POST has no size limitations, and can be used to send large
amounts of data.
Form submissions with POST cannot be bookmarked
Tip: Always use POST if the form data contains sensitive or personal information!
Example
Example
A form with a novalidate attribute:
Exercise:
Add a submit button, and specify that the form should go to
"/action_page.php".
<form ="/action_page.php">
Name: <input type="text" name="name">
<>
</form>
novalidate Specifies that the form should not be validated when submitted
<input>
<label>
<select>
<textarea>
<button>
<fieldset>
<legend>
<datalist>
<output>
<option>
<optgroup>
Example
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
The <label> element also help users who have difficulty clicking on very
small regions (such as radio buttons or checkboxes) - because when the
user clicks the text within the <label> element, it toggles the radio
button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.
The <select> Element
The <select> element defines a drop-down list:
Example
Example
Visible Values:
Use the size attribute to specify the number of visible values:
Example
Example
Example
The rows attribute specifies the visible number of lines in a text area.
You can also define the size of the text area by using CSS:
Example
<textarea name="message" style="width:200px; height:600px;">
The cat was playing in the garden.
</textarea>
Example
Note: Always specify the type attribute for the button element. Different
browsers may use different default types for the button element.
Example
<form action="/action_page.php">
<fieldset>
<legend>Personalia:</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
Users will see a drop-down list of the pre-defined options as they input
data.
The list attribute of the <input> element, must refer to the id attribute
of the <datalist> element.
Example
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
Example
<form action="/action_page.php"
oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>
Exercise:
In the form below, add an empty drop down list with the name "cars".
<form action="/action_page.php">
<>
</>
</form>
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
Example
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd">
</form>
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
If you omit the submit button's value attribute, the button will get a
default text:
Example
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
If you change the input values and then click the "Reset" button, the
form-data will be reset to the default values.
Radio buttons let a user select ONLY ONE of a limited number of choices:
Example
<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaSc
ript">
<label for="javascript">JavaScript</label>
</form>
Example
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
Example
Example
<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>
Example
<form>
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
</form>
You can also use the min and max attributes to add restrictions to dates:
Example
<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-
31"><br><br>
<label for="datemin">Enter a date after 2000-01-01:</label>
<input type="date" id="datemin" name="datemin" min="2000-01-02">
</form>
Input Type Datetime-local
The <input type="datetime-local"> specifies a date and time input field,
with no time zone.
Example
<form>
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
</form>
Some smartphones recognize the email type, and add ".com" to the
keyboard to match email input.
Example
<form>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
</form>
<form>
<input type="image" src="img_submit.gif" alt="Submit" width="48" height
="48">
</form>
Example
<form>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
</form>
A hidden field lets web developers include data that cannot be seen or
modified by users when a form is submitted.
Note: While the value is not displayed to the user in the page's content,
it is visible (and can be edited) using any browser's developer tools or
"View Source" functionality. Do not use hidden inputs as a form of
security!
Example
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="hidden" id="custId" name="custId" value="3487">
<input type="submit" value="Submit">
</form>
Example
<form>
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth">
</form>
The following example displays a numeric input field, where you can
enter a value from 1 to 5:
Example
<form>
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>
Input Restrictions
Here is a list of some common input restrictions:
Attribute Description
You will learn more about input restrictions in the next chapter.
The following example displays a numeric input field, where you can
enter a value from 0 to 100, in steps of 10. The default value is 30:
Example
<form>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="0" max="100"
step="10" value="30">
</form>
Input Type Range
The <input type="range"> defines a control for entering a number whose
exact value is not important (like a slider control). Default range is 0 to
100. However, you can set restrictions on what numbers are accepted
with the min, max, and step attributes:
Example
<form>
<label for="vol">Volume (between 0 and 50):</label>
<input type="range" id="vol" name="vol" min="0" max="50">
</form>
Example
<form>
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
</form>
Example
<form>
<label for="phone">Enter your phone number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{2}-
[0-9]{3}">
</form>
Example
<form>
<label for="appt">Select a time:</label>
<input type="time" id="appt" name="appt">
</form>
Some smartphones recognize the url type, and adds ".com" to the
keyboard to match url input.
<form>
<label for="homepage">Add your homepage:</label>
<input type="url" id="homepage" name="homepage">
</form>
Example
<form>
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
</form>
Exercise:
In the form below, add an input field for text, with the name "username" .
<form action="/action_page.php">
<>
</form>
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
A read-only input field cannot be modified (however, a user can tab to it,
highlight it, and copy the text from it).
The value of a read-only input field will be sent when submitting the form!
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" readonly><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
The value of a disabled input field will not be sent when submitting the
form!
Note: The size attribute works with the following input types: text,
search, tel, url, email, and password.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" size="4">
</form>
Note: When a maxlength is set, the input field will not accept more than
the specified number of characters. However, this attribute does not
provide any feedback. So, if you want to alert the user, you must write
JavaScript code.
Example
The min and max attributes work with the following input types: number,
range, date, datetime-local, month, time and week.
Tip: Use the max and min attributes together to create a range of legal
values.
<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-
31"><br><br>
The multiple attribute works with the following input types: email, and
file.
The pattern attribute works with the following input types: text, date,
search, url, tel, email, and password.
Tip: Use the global title attribute to describe the pattern to help the user.
The short hint is displayed in the input field before the user enters a
value.
The placeholder attribute works with the following input types: text,
search, url, tel, email, and password.
<form>
<label for="phone">Enter a phone number:</label>
<input type="tel" id="phone" name="phone"
placeholder="123-45-678"
pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
</form>
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</form>
Tip: This attribute can be used together with the max and min attributes
to create a range of legal values.
The step attribute works with the following input types: number, range,
date, datetime-local, month, time and week.
Example
An input field with a specified legal number intervals:
<form>
<label for="points">Points:</label>
<input type="number" id="points" name="points" step="3">
</form>
Note: Input restrictions are not foolproof, and JavaScript provides many
ways to add illegal input. To safely restrict input, it must also be checked by
the receiver (the server)!
Example
Let the "First name" input field automatically get focus when the page loads:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" autofocus><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
Tip: Always specify both the height and width attributes for images. If height
and width are set, the space required for the image is reserved when the page
is loaded. Without these attributes, the browser does not know the size of the
image, and cannot reserve the appropriate space to it. The effect will be that
the page layout will change during loading (while the images load).
Example
Define an image as the submit button, with height and width attributes:
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48"
height="48">
</form>
Example
An <input> element with pre-defined values in a <datalist>:
<form>
<input list="browsers">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
Autocomplete allows the browser to predict the value. When a user starts
to type in a field, the browser should display options to fill in the field,
based on earlier typed values.
Example
An HTML form with autocomplete on, and off for one input field:
Exercise:
In the input field below, add placeholder that says "Your name here".
<form action="/action_page.php">
<input type="text" >
</form>
Example
An input field located outside of the HTML form (but still a part of the form):
Note: This attribute overrides the action attribute of the <form> element.
The formaction attribute works with the following input types: submit and
image.
Example
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formaction="/action_page2.php" value="Submit as
Admin">
</form>
The formenctype attribute works with the following input types: submit
and image.
Example
A form with two submit buttons. The first sends the form-data with default
encoding, the second sends the form-data encoded as "multipart/form-data":
Note: This attribute overrides the method attribute of the <form> element.
The formmethod attribute works with the following input types: submit and
image.
Example
A form with two submit buttons. The first sends the form-data with
method="get". The second sends the form-data with method="post":
Note: This attribute overrides the target attribute of the <form> element.
The formtarget attribute works with the following input types: submit and
image.
Example
A form with two submit buttons, with different target windows
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formtarget="_blank" value="Submit to a new
window/tab">
</form>
The formnovalidate attribute works with the following input types: submit.
Example
<form action="/action_page.php">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
<input type="submit" formnovalidate="formnovalidate"
value="Submit without validation">
</form>
When present, novalidate specifies that all of the form-data should not be
validated when submitted.
Example
Specify that no form-data should be validated on submit:
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid gray;
padding: 8px;
}
h1 {
text-align: center;
text-transform: uppercase;
color: #4CAF50;
}
p{
text-indent: 50px;
text-align: justify;
letter-spacing: 3px;
}
a{
text-decoration: none;
color: #008CBA;
}
</style>
</head>
<body>
<div>
<h1>text formatting</h1>
<p>This text is styled with some of the text formatting properties. The heading uses the text-
align, text-transform, and color properties.
The paragraph is indented, aligned, and the space between characters is specified. The underline
is removed from this colored
<a target="_blank" href="tryit.asp?filename=trycss_text">"Try it Yourself"</a> link.</p>
</div>
</body>
</html>
Text Color
The color property is used to set the color of the text. The color is
specified by:
The default text color for a page is defined in the body selector.
body {
color: blue;
}
h1 {
color: green;
}
Example
body {
background-color: lightgrey;
color: blue;
}
h1 {
background-color: black;
color: white;
}
div {
background-color: blue;
color: white;
}
Important: High contrast is very important for people with vision problems. So,
always ensure that the contrast between the text color and the background
color (or background image) is good!
text-align
text-align-last
direction
unicode-bidi
vertical-align
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
The following example shows center aligned, and left and right aligned
text (left alignment is default if text direction is left-to-right, and right
alignment is default if text direction is right-to-left):
Example
h1 {
text-align: center;
}
h2 {
text-align: left;
}
h3 {
text-align: right;
}
div {
text-align: justify;
}
Text Align Last
The text-align-last property specifies how to align the last line of a text.
Example
p.a {
text-align-last: right;
}
p.b {
text-align-last: center;
}
p.c {
text-align-last: justify;
}
Text Direction
The direction and unicode-bidi properties can be used to change the
text direction of an element:
Example
p {
direction: rtl;
unicode-bidi: bidi-override;
}
<body>
Vertical Alignment
The vertical-align property sets the vertical alignment of an element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
img.a {
vertical-align: baseline;
}
img.b {
vertical-align: text-top;
}
img.c {
vertical-align: text-bottom;
}
img.d {
vertical-align: sub;
}
img.e {
vertical-align: super;
}
</style>
</head>
<body>
<h2>vertical-align: text-top:</h2>
<p>An <img class="b" src="sqpurple.gif" width="9" height="9"> image with a text-top
alignment.</p>
<h2>vertical-align: text-bottom:</h2>
<p>An <img class="c" src="sqpurple.gif" width="9" height="9"> image with a text-bottom
alignment.</p>
<h2>vertical-align: sub:</h2>
<p>An <img class="d" src="sqpurple.gif" width="9" height="9"> image with a sub
alignment.</p>
<h2>vertical-align: sup:</h2>
<p>An <img class="e" src="sqpurple.gif" width="9" height="9"> image with a super
alignment.</p>
</body>
</html>
text-decoration-line
text-decoration-color
text-decoration-style
text-decoration-thickness
text-decoration
Tip: You can combine more than one value, like overline and underline to
display lines both over and under a text.
Example
h1 {
text-decoration-line: overline;
}
h2 {
text-decoration-line: line-through;
}
h3 {
text-decoration-line: underline;
}
p {
text-decoration-line: overline underline;
}
Note: It is not recommended to underline text that is not a link, as this often
confuses the reader.
h1 {
text-decoration-line: overline;
text-decoration-color: red;
}
h2 {
text-decoration-line: line-through;
text-decoration-color: blue;
}
h3 {
text-decoration-line: underline;
text-decoration-color: green;
}
p {
text-decoration-line: overline underline;
text-decoration-color: purple;
}
h1 {
text-decoration-line: underline;
text-decoration-style: solid;
}
h2 {
text-decoration-line: underline;
text-decoration-style: double;
}
h3 {
text-decoration-line: underline;
text-decoration-style: dotted;
}
p.ex1 {
text-decoration-line: underline;
text-decoration-style: dashed;
}
p.ex2 {
text-decoration-line: underline;
text-decoration-style: wavy;
}
p.ex3 {
text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: wavy;
}
Example
h1 {
text-decoration-line: underline;
text-decoration-thickness: auto;
}
h2 {
text-decoration-line: underline;
text-decoration-thickness: 5px;
}
h3 {
text-decoration-line: underline;
text-decoration-thickness: 25%;
}
p {
text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: double;
text-decoration-thickness: 5px;
}
The Shorthand Property
The text-decoration property is a shorthand property for:
text-decoration-line (required)
text-decoration-color (optional)
text-decoration-style (optional)
text-decoration-thickness (optional)
Example
h1 {
text-decoration: underline;
}
h2 {
text-decoration: underline red;
}
h3 {
text-decoration: underline red double;
}
p {
text-decoration: underline red double 5px;
}
A Small Tip
All links in HTML are underlined by default. Sometimes you see that links
are styled with no underline. The text-decoration: none; is used to
remove the underline from links, like this:
Example
a {
text-decoration: none;
}
All CSS text-decoration Properties
Property Description
CSS Text
Transformation
Text Transformation
The text-transform property is used to specify uppercase and lowercase
letters in a text.
Example
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
text-indent
letter-spacing
line-height
word-spacing
white-space
Text Indentation
The text-indent property is used to specify the indentation of the first
line of a text:
Example
p {
text-indent: 50px;
}
Letter Spacing
The letter-spacing property is used to specify the space between the
characters in a text.
Example
h1 {
letter-spacing: 5px;
}
h2 {
letter-spacing: -2px;
}
Line Height
The line-height property is used to specify the space between lines:
Example
p.small {
line-height: 0.8;
}
p.big {
line-height: 1.8;
}
Word Spacing
The word-spacing property is used to specify the space between the
words in a text.
The following example demonstrates how to increase or decrease the
space between words:
Example
p.one {
word-spacing: 10px;
}
p.two {
word-spacing: -2px;
}
White Space
The white-space property specifies how white-space inside an element is
handled.
Example
p {
white-space: nowrap;
}
In its simplest use, you only specify the horizontal shadow (2px) and the
vertical shadow (2px):
Example 1
h1 {
color: white;
text-shadow: 2px 2px 4px #000000;
}
Example 2
Text-shadow with red neon glow:
h1 {
text-shadow: 0 0 3px #ff0000;
}
Example 3
Text-shadow with red and blue neon glow:
h1 {
text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff;
}
Example 4
h1 {
color: white;
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}
Exercise:
Change the text color of all <p> elements to "red".
<style>
p{
: red;
}
</style>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</body>
CSS Fonts
Choosing the right font for your website is important!
The right font can create a strong identity for your brand.
Using a font that is easy to read is important. The font adds value to your
text. It is also important to choose the correct color and text size for the
font.
1. Serif fonts have a small stroke at the edges of each letter. They
create a sense of formality and elegance.
2. Sans-serif fonts have clean lines (no small strokes attached). They
create a modern and minimalistic look.
3. Monospace fonts - here all the letters have the same fixed width.
They create a mechanical look.
4. Cursive fonts imitate human handwriting.
5. Fantasy fonts are decorative/playful fonts.
All the different font names belong to one of the generic font families.
Example
.p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}
Fallback Fonts
However, there are no 100% completely web safe fonts. There is always
a chance that a font is not found or is not installed properly.
This means that you should add a list of similar "backup fonts" in
the font-family property. If the first font does not work, the browser will
try the next one, and the next one, and so on. Always end the list with a
generic font family name.
Example
Here, there are three font types: Tahoma, Verdana, and sans-serif. The
second and third fonts are backups, in case the first one is not found.
p {
font-family: Tahoma, Verdana, sans-serif;
}
Arial (sans-serif)
Verdana (sans-serif)
Tahoma (sans-serif)
Trebuchet MS (sans-serif)
Times New Roman (serif)
Georgia (serif)
Garamond (serif)
Courier New (monospace)
Brush Script MT (cursive)
Note: Before you publish your website, always check how your fonts appear on
different browsers and devices, and always use fallback fonts!
Arial (sans-serif)
Arial is the most widely used font for both online and printed media. Arial
is also the default font in Google Docs.
Arial is one of the safest web fonts, and it is available on all major
operating systems.
Example
0123456789
Verdana (sans-serif)
Verdana is a very popular font. Verdana is easily readable even for small
font sizes.
Example
0123456789
Tahoma (sans-serif)
The Tahoma font has less space between the characters.
Example
0123456789
Trebuchet MS (sans-serif)
Trebuchet MS was designed by Microsoft in 1996. Use this font carefully.
Not supported by all mobile operating systems.
Example
Lorem ipsum dolor sit
amet
Lorem ipsum dolor sit amet.
0123456789
Example
0123456789
Georgia (serif)
Georgia is an elegant serif font. It is very readable at different font sizes,
so it is a good candidate for mobile-responsive design.
Example
0123456789
Garamond (serif)
Garamond is a classical font used for many printed books. It has a
timeless look and good readability.
Example
Lorem ipsum dolor sit
amet
Lorem ipsum dolor sit amet.
0123456789
Example
0 1 2 3 4 5 6 7 8 9
Brush Script MT (cursive)
The Brush Script MT font was designed to mimic handwriting. It is
elegant and sophisticated, but can be hard to read. Use it carefully.
Example
0123456789
Tip: Also check out all available Google Fonts and how to use them.
Serif
Sans-serif
Monospace
Cursive
Fantasy
Serif Fonts
font-family Example text
Georgia, serif
This is a
Heading
This is a paragraph.
Garamond, serif
This is a
Heading
This is a paragraph.
Sans-Serif Fonts
font-family Example text
Monospace Fonts
font-family Example text
This is
"Courier New", Courier, monospace
a
Heading
This is a
paragraph.
Cursive Fonts
font-family Example text
Tip: Also check out all available Google Fonts and how to use them.
Example
p.normal {
font-style: normal;
}
p.italic {
font-style: italic;
}
p.oblique {
font-style: oblique;
}
Font Weight
The font-weight property specifies the weight of a font:
Example
p.normal {
font-weight: normal;
}
p.thick {
font-weight: bold;
}
Font Variant
The font-variant property specifies whether or not a text should be
displayed in a small-caps font.
Example
p.normal {
font-variant: normal;
}
p.small {
font-variant: small-caps;
}
Being able to manage the text size is important in web design. However,
you should not use font size adjustments to make paragraphs look like
headings, or headings look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and
<p> for paragraphs.
Absolute size:
Relative size:
Note: If you do not specify a font size, the default size for normal text, like
paragraphs, is 16px (16px=1em).
Example
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p {
font-size: 14px;
}
Tip: If you use pixels, you can still use the zoom tool to resize the entire
page.
1em is equal to the current font size. The default text size in browsers is
16px. So, the default size of 1em is 16px.
Example
h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}
h2 {
font-size: 1.875em; /* 30px/16=1.875em */
}
p {
font-size: 0.875em; /* 14px/16=0.875em */
}
In the example above, the text size in em is the same as the previous
example in pixels. However, with the em size, it is possible to adjust the
text size in all browsers.
Example
body {
font-size: 100%;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.875em;
}
p {
font-size: 0.875em;
}
Our code now works great! It shows the same text size in all browsers,
and allows all browsers to zoom or resize the text!
That way the text size will follow the size of the browser window:
Google Fonts are free to use, and have more than 1000 fonts to choose
from.
Example
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=So
fia">
<style>
body {
font-family: "Sofia", sans-serif;
}
</style>
</head>
Example
Here, we want to use a font named "Trirong" from Google Fonts:
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?famil
y=Trirong">
<style>
body {
font-family: "Trirong", serif;
}
</style>
</head>
Example
Here, we want to use a font named "Audiowide" from Google Fonts:
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?famil
y=Audiowide">
<style>
body {
font-family: "Audiowide", sans-serif;
}
</style>
</head>
Note: Requesting multiple fonts may slow down your web pages! So be
careful about that.
Example
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=So
fia">
<style>
body {
font-family: "Sofia", sans-serif;
font-size: 30px;
text-shadow: 3px 3px 3px #ababab;
}
</style>
</head>
Enabling Font Effects
Google has also enabled different font effects that you can use.
First add effect=effectname to the Google API, then add a special class
name to the element that is going to use the special effect. The class
name always starts with font-effect- and ends with the effectname.
Example
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=So
fia&effect=fire">
<style>
body {
font-family: "Sofia", sans-serif;
font-size: 30px;
}
</style>
</head>
<body>
</body>
To request multiple font effects, just separate the effect names with a
pipe character (|), like this:
Example
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=So
fia&effect=neon|outline|emboss|shadow-multiple">
<style>
body {
font-family: "Sofia", sans-serif;
font-size: 30px;
}
</style>
</head>
<body>
</body>
To request multiple font effects, just separate the effect names with a
pipe character (|), like this:
Example
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=So
fia&effect=neon|outline|emboss|shadow-multiple">
<style>
body {
font-family: "Sofia", sans-serif;
font-size: 30px;
}
</style>
</head>
<body>
</body>
CSS Great Font
Pairings
Great font pairings are essential to great design.
1. Complement
It is always safe to find font pairings that complement one another.
For example, the Lucida superfamily contains the following fonts: Lucida
Sans, Lucida Serif, Lucida Typewriter Sans, Lucida Typewriter Serif and
Lucida Math.
3. Contrast is King
Two fonts that are too similar will often conflict. However, contrasts, done
the right way, brings out the best in each font.
A strong superfamily includes both serif and sans serif variations of the
same font (e.g. Lucida and Lucida Sans).
Example
body {
background-color: black;
font-family: Verdana, sans-serif;
font-size: 16px;
color: gray;
}
h1 {
font-family: Georgia, serif;
font-size: 60px;
color: white;
}
Below, we have shown some popular font pairings that will suit many
brands and contexts.
Example
Use the "Georgia" font for headings, and "Verdana" for text:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
font-family: Verdana, sans-serif;
font-size: 16px;
color: gray;
}
h1 {
font-family: Georgia, serif;
font-size: 60px;
color: white;
}
</style>
</head>
<body>
<h1>Beautiful Norway</h1>
<p>Norway has a total area of 385,252 square kilometers and a population of 5,438,657
(December 2020). Norway is bordered by Sweden, Finland and Russia to the north-east, and the
Skagerrak to the south, with Denmark on the other side.</p>
<p>Norway has beautiful mountains, glaciers and stunning fjords. Oslo, the capital, is a city of
green spaces and museums. Bergen, with colorful wooden houses, is the starting point for cruises
to the dramatic Sognefjord. Norway is also known for fishing, hiking and skiing.</p>
</body>
</html>
Beautiful Norway
Norway has a total area of 385,252 square kilometers and a
population of 5,438,657 (December 2020). Norway is bordered by
Sweden, Finland and Russia to the north-east, and the Skagerrak to
the south, with Denmark on the other side.
font-style
font-variant
font-weight
font-size/line-height
font-family
Note: The font-size and font-family values are required. If one of the
other values is missing, their default value are used.
Example
p.a {
font: 20px Arial, sans-serif;
}
p.b {
font: italic small-caps bold 12px/30px Georgia, serif;
}
Exercise:
Set the font for <h1> to "Verdana".
<style>
h1 {
: Verdana;
}
</style>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</body>
CSS Pseudo-
classes
What are Pseudo-classes?
A pseudo-class is used to define a special state of an element.
Syntax
The syntax of pseudo-classes:
selector:pseudo-class {
property: value;
}
Anchor Pseudo-classes
Links can be displayed in different ways:
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* selected link */
a:active {
color: #0000FF;
}
Note: a:hover MUST come after a:link and a:visited in the CSS
definition in order to be effective! a:active MUST come after a:hover in
the CSS definition in order to be effective! Pseudo-class names are not
case-sensitive.
When you hover over the link in the example, it will change color:
Example
a.highlight:hover {
color: #ff0000;
}
Hover on <div>
An example of using the :hover pseudo-class on a <div> element:
Example
div:hover {
background-color: blue;
}
div:hover p {
display: block;
}
Example
p:first-child {
color: blue;
}
Example
p i:first-child {
color: blue;
}
Example
p:first-child i {
color: blue;
}
In the example below, :lang defines the quotation marks for <q>
elements with lang="no":
Example
<html>
<head>
<style>
q:lang(no) {
quotes: "~" "~";
}
</style>
</head>
<body>
</body>
</html>
Exercise:
Set the background-color to red, when you mouse over a link.
<style> {
background-color: red;
}
</style>
<body>
<h1>This is a header.</h1>
<p>This is a paragraph.</p>
<a href="https://w3schools.com">This is a link.</a>
</body>
CSS Pseudo-elements
What are Pseudo-Elements?
A CSS pseudo-element is used to style specified parts of an element.
Syntax
The syntax of pseudo-elements:
selector::pseudo-element {
property:value;
}
The single-colon syntax was used for both pseudo-classes and pseudo-
elements in CSS2 and CSS1.
The following example formats the first line of the text in all <p>
elements:
Example
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
font properties
color properties
background properties
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
line-height
clear
The following example formats the first letter of the text in all <p>
elements:
Example
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
font properties
color properties
background properties
margin properties
padding properties
border properties
text-decoration
vertical-align (only if "float" is "none")
text-transform
line-height
float
clear
Example
p.intro::first-letter {
color: #ff0000;
font-size:200%;
}
The example above will display the first letter of paragraphs with
class="intro", in red and in a larger size.
Multiple Pseudo-elements
Several pseudo-elements can also be combined.
Example
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
p::first-line {
color: #0000ff;
font-variant: small-caps;
}
The following example inserts an image before the content of each <h1>
element:
Example
h1::before {
content: url(smiley.gif);
}
The following example inserts an image after the content of each <h1>
element:
Example
h1::after {
content: url(smiley.gif);
}
Example
::selection {
color: red;
background: yellow;
}
*Week 6:*
The <canvas> element is only a container for graphics. You must use
JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas
has no border and no content.
Add a JavaScript
After creating the rectangular canvas area, you must add a JavaScript to
do the drawing.
Draw a Line
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
Draw a Circle
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
Draw a Text
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
</script>
Stroke Text
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
</script>
// Create gradient
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Create gradient
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
Draw Image
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
</script>
What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define graphics for the Web
SVG is a W3C recommendation
SVG has several methods for drawing paths, boxes, circles, text, and
graphic images.
SVG Circle
Example
<!DOCTYPE html>
<html>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-
width="4" fill="yellow" />
</svg>
</body>
</html>
SVG Rectangle
Example
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-
width:10;stroke:rgb(0,0,0)" />
</svg>
SVG Star
Example
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-
rule:evenodd;" />
</svg>
SVG Logo
Example
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-
opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-
opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-
family="Verdana" x="50" y="86">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>
SVG is XML based, which means that every element is available within
the SVG DOM. You can attach JavaScript event handlers for an element.
Canvas SVG
HTML Multimedia(Audi
o and Video)
Multimedia on the web is sound, music, videos, movies, and
animations.
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything
you can hear or see, like images, music, sound, videos, records, films,
animations, and more.
Browser Support
The first web browsers had support for text only, limited to a single font
in a single color.
Later came browsers with support for colors, fonts, images, and
multimedia!
Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file
extension.
Note: Only MP4, WebM, and Ogg video are supported by the HTML standard.
MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3
is the most popular format for music players. Combines
good compression (small files) with high quality.
Supported by all browsers.
MP4 .mp4 MP4 is a video format, but can also be used for audio.
Supported by all browsers.
Note: Only MP3, WAV, and Ogg audio are supported by the HTML standard.
HTML Video
<!DOCTYPE html>
<html>
<body>
<p>
Video courtesy of
<a href="https://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.
</p>
</body>
</html>
The <source> element allows you to specify alternative video files which
the browser may choose from. The browser will use the first recognized
format.
The text between the <video> and </video> tags will only be displayed in
browsers that do not support the <video> element.
Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Add muted after autoplay to let your video start playing automatically (but
muted):
Example
MP4 video/mp4
WebM video/webm
Ogg video/ogg
There are also DOM events that can notify you when a video begins to
play, is paused, etc.
<!DOCTYPE html>
<html>
<body>
<div style="text-align:center">
<button onclick="playPause()">Play/Pause</button>
<button onclick="makeBig()">Big</button>
<button onclick="makeSmall()">Small</button>
<button onclick="makeNormal()">Normal</button>
<br><br>
<video id="video1" width="420">
<source src="mov_bbb.mp4" type="video/mp4">
<source src="mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML video.
</video>
</div>
<script>
var myVideo = document.getElementById("video1");
function playPause() {
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
function makeBig() {
myVideo.width = 560;
}
function makeSmall() {
myVideo.width = 320;
}
function makeNormal() {
myVideo.width = 420;
}
</script>
</body>
</html>
HTML Audio
The HTML <audio> element is used to play an audio file on a web
page.
Example
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
The <source> element allows you to specify alternative audio files which
the browser may choose from. The browser will use the first recognized
format.
The text between the <audio> and </audio> tags will only be displayed in
browsers that do not support the <audio> element.
Example
Add muted after autoplay to let your audio file start playing automatically
(but muted):
Example
MP3 audio/mpeg
OGG audio/ogg
WAV audio/wav
This allows you to load, play, and pause audios, as well as set duration
and volume.
There are also DOM events that can notify you when an audio begins to
play, is paused, etc.
HTML Audio Tags
Tag Description
An easier solution is to let YouTube play the videos in your web page.
YouTube Video Id
YouTube will display an id (like tgbNymZ7vqY), when you save (or play)
a video.
You can use this id, and refer to your video in the HTML code.
Add mute=1 after autoplay=1 to let your video start playing automatically
(but muted).
YouTube Playlist
A comma separated list of videos to play (in addition to the original URL).
YouTube Loop
Add loop=1 to let your video loop forever.
YouTube Controls
Add controls=0 to not display controls in the video player.
YouTube - Controls
CSS Transitio
ns
CSS Transitions
CSS transitions allows you to change property values smoothly, over a
given duration.
Note: If the duration part is not specified, the transition will have no
effect, because the default value is 0.
The following example shows a 100px * 100px red <div> element. The
<div> element has also specified a transition effect for the width
property, with a duration of 2 seconds:
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}
div:hover {
width: 300px;
}
</style>
</head>
<body>
<h1>The transition Property</h1>
</body>
</html>
The transition effect will start when the specified CSS property (width)
changes value.
Now, let us specify a new value for the width property when a user
mouses over the <div> element:
Example
div:hover {
width: 300px;
}
Notice that when the cursor mouses out of the element, it will gradually
change back to its original style.
div {
transition: width 2s, height 4s;
}
div:hover {
width: 300px;
height: 300px;
}
Specify the Speed Curve of the
Transition
The transition-timing-function property specifies the speed curve of
the transition effect.
ease - specifies a transition effect with a slow start, then fast, then
end slowly (this is default)
linear - specifies a transition effect with the same speed from start
to end
ease-in - specifies a transition effect with a slow start
ease-out - specifies a transition effect with a slow end
ease-in-out - specifies a transition effect with a slow start and end
cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-
bezier function
The following example shows some of the different speed curves that can
be used:
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}
div:hover {
width: 300px;
}
</style>
</head>
<body>
<p>Hover over the div elements below, to see the different speed
curves:</p>
<div id="div1">linear</div><br>
<div id="div2">ease</div><br>
<div id="div3">ease-in</div><br>
<div id="div4">ease-out</div><br>
<div id="div5">ease-in-out</div><br>
</body>
</html>
Example
div {
transition-delay: 1s;
}
Transition + Transformation
The following example adds a transition effect to the transformation:
Example
div {
transition: width 2s, height 2s, transform 2s;
}
Example
div {
transition-property: width;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
Example
div {
transition: width 2s linear 1s;
}
Exercise:
Add a 2 second transition effect for width changes of the <div> element.
<style>
div {
width: 100px;
height: 100px;
background: red;
: ;
}
div:hover {
width: 300px;
}
</style>
<body>
<div>This is a div</div>
</body>
Property Description
CSS Animatio
ns
CSS Animations
CSS allows animation of HTML elements without using JavaScript or Flash!
@keyframes
animation-name
animation-duration
animation-delay
animation-iteration-count
animation-direction
animation-timing-function
animation-fill-mode
animation
You can change as many CSS properties you want, as many times as you
want.
To use CSS animation, you must first specify some keyframes for the
animation.
Keyframes hold what styles the element will have at certain times.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
</style>
</head>
<body>
<h1>CSS Animation</h1>
<div></div>
</body>
</html>
Note: The animation-duration property defines how long an animation
should take to complete. If the animation-duration property is not
specified, no animation will occur, because the default value is 0s (0
seconds).
In the example above we have specified when the style will change by
using the keywords "from" and "to" (which represents 0% (start) and
100% (complete)).
It is also possible to use percent. By using percent, you can add as many
style changes as you like.
The following example will change both the background-color and the
position of the <div> element when the animation is 25% complete, 50%
complete, and again when the animation is 100% complete:
Example
Delay an Animation
The animation-delay property specifies a delay for the start of an
animation.
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-delay: 2s;
}
Negative values are also allowed. If using negative values, the animation
will start as if it had already been playing for N seconds.
In the following example, the animation will start as if it had already been
playing for 2 seconds:
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-delay: -2s;
}
The following example will run the animation 3 times before it stops:
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
}
The following example uses the value "infinite" to make the animation
continue for ever:
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: infinite;
}
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-direction: reverse;
}
The following example uses the value "alternate" to make the animation
run forwards first, then backwards:
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 2;
animation-direction: alternate;
}
Example
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 2;
animation-direction: alternate-reverse;
}
ease - Specifies an animation with a slow start, then fast, then end
slowly (this is default)
linear - Specifies an animation with the same speed from start to
end
ease-in - Specifies an animation with a slow start
ease-out - Specifies an animation with a slow end
ease-in-out - Specifies an animation with a slow start and end
cubic-bezier(n,n,n,n) - Lets you define your own values in a cubic-
bezier function
The following example shows some of the different speed curves that can
be used:
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 50px;
background-color: red;
font-weight: bold;
position: relative;
animation: mymove 5s infinite;
}
#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}
@keyframes mymove {
from {left: 0px;}
to {left: 300px;}
}
</style>
</head>
<body>
<h1>CSS Animation</h1>
<div id="div1">linear</div>
<div id="div2">ease</div>
<div id="div3">ease-in</div>
<div id="div4">ease-out</div>
<div id="div5">ease-in-out</div>
</body>
</html>
none - Default value. Animation will not apply any styles to the
element before or after it is executing
forwards - The element will retain the style values that is set by the
last keyframe (depends on animation-direction and animation-
iteration-count)
backwards - The element will get the style values that is set by the
first keyframe (depends on animation-direction), and retain this
during the animation-delay period
both - The animation will follow the rules for both forwards and
backwards, extending the animation properties in both directions
The following example lets the <div> element retain the style values
from the last keyframe when the animation ends:
Example
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-fill-mode: forwards;
}
The following example lets the <div> element get the style values set by
the first keyframe before the animation starts (during the animation-
delay period):
Example
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-delay: 2s;
animation-fill-mode: backwards;
}
The following example lets the <div> element get the style values set by
the first keyframe before the animation starts, and retain the style values
from the last keyframe when the animation ends:
Example
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-delay: 2s;
animation-fill-mode: both;
}
Example
div {
animation-name: example;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
The same animation effect as above can be achieved by using the
shorthand animation property:
Example
div {
animation: example 5s linear 2s infinite alternate;
}
Exercise:
Add a 2 second animation for the <div> element, which changes the
color from red to blue. Call the animation "example".
<style>
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: ;
: 2s;
}
@keyframes example {
from {: red;}
to {: blue;}
}
</style>
<body>
<div>This is a div</div>
</body>
CSS Animation Properties
The following table lists the @keyframes rule and all the CSS animation
properties:
Property Description
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
Learning Speed
In this lesson, the learning speed is your choice.
Everything is up to you.
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
JavaScript accepts both double and single quotes: like so
<!DOCTYPE html>
<html>
<body>
<p>In this case JavaScript changes the value of the src (source)
attribute of an image.</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.
gif'">Turn on the light</button>
<button
onclick="document.getElementById('myImage').src='pic_bulboff.
gif'">Turn off the light</button>
</body>
</html>
document.getElementById("demo").style.fontSize = "35px";
document.getElementById("demo").style.display = "none";
Example
document.getElementById("demo").style.display = "block";
JavaScript Where To
The <script> Tag
In HTML, JavaScript code is inserted
between <script> and </script> tags.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
For example, a function can be called when an event occurs, like when
the user clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of
an HTML page.
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
</body>
</html>
JavaScript in <body>
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Placing scripts at the bottom of the <body> element improves the display speed,
because script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many
different web pages.
Example
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag
is located.
To add several script files to one page - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
An external script can be referenced in 3 different ways:
Example
<script src="https://www.javascript.com/js/myScript.js"></script>
Example
<script src="/js/myScript.js"></script>
Example
<script src="myScript.js"></script>
JavaScript Comments
JavaScript comments can be used to explain JavaScript code,
and to make it more readable.
Any text between // and the end of the line will be ignored by JavaScript
(will not be executed).
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
his example uses a single line comment at the end of each line to explain
the code:
Example
Multi-line Comments
Multi-line comments start with /* and end with */.
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Example
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Variables
Variables are Containers for Storing Data
Automatically
Using var
Using let
Using const
Example
x = 5;
y = 6;
z = x + y;
Note
It is considered good programming practice to always declare variables before
use.
var x = 5;
var y = 6;
var z = x + y;
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price1 and price2 are declared with the const keyword.
3. Always use const if the type should not be changed (Arrays and Objects)
let x = 5;
let y = 6;
let z = x + y;
From the example above, you can guess that the total is calculated to be
11.
Note
Variables are containers for storing values.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
Note
JavaScript identifiers are case-sensitive.
This is different from algebra. The following does not make sense in
algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x
is incremented by 5.)
Note
The "equal to" operator is written like == in JavaScript.
JavaScript can handle many types of data, but for now, just think of
numbers and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the
value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Note
It's a good programming practice to declare all variables at the beginning of a
script.
Start the statement with let and separate the variables by comma:
Example
Example
The variable carName will have the value undefined after the execution of
this statement:
Example
let carName;
The variable carName will still have the value "Volvo" after the execution
of these statements:
Example
Note
You cannot re-declare a variable declared with let or const.
Example
let x = 5 + 2 + 3;
Example
Example
let x = "5" + 2 + 3;
Note
If you put a number in quotes, the rest of the numbers will be treated as strings,
and concatenated.
Example
let x = 2 + 3 + "5";
JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing
$ are valid variable names:
Example
Using the dollar sign is not very common in JavaScript, but professional
programmers often use it as an alias for the main function in a JavaScript
library.
In the JavaScript library jQuery, for instance, the main function $ is used
to select HTML elements. In jQuery $("p"); means "select all p elements".
Example
Exercise:
Create a variable called carName and assign the value Volvo to it.
JavaScript Da
ta Types
JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
Note
A JavaScript variable can hold any type of data.
let x = 16 + "Volvo";
Note
When adding a number and a string, JavaScript will treat the number as a string.
Example
let x = 16 + "Volvo";
Example
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
In the second example, since the first operand is a string, all operands
are treated as strings.
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
Note
Most programming languages have many number types:
JavaScript BigInt
All JavaScript numbers are stored in a a 64-bit floating-point format.
Example
let x = BigInt("123456789012345678901234567890");
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Example
Array indexes are zero-based, which means the first item is [0], second is
[1], and so on.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Example
Example
Example
Undefined
In JavaScript, a variable without a value, has the value undefined. The
type is also undefined.
Example
Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
Example
Exercise:
Use comments to describe the correct data type of the following variables:
HTML Iframes
An HTML iframe is used to display a web page within a web
page.
Example
Example
To remove the border, add the style attribute and use the
CSS border property:
Example
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>
With CSS, you can also change the size, style and color of the iframe's
border:
Example
The target attribute of the link must refer to the name attribute of the
iframe:
Example
Chapter Summary
The HTML <iframe> tag specifies an inline frame
The src attribute defines the URL of the page to embed
Always include a title attribute (for screen readers)
The height and width attributes specify the size of the iframe
Use border:none; to remove the border around the iframe
Exercise:
Create an iframe with a URL address that goes to
https://www.facebook.com.
<iframe ="https://www.facebook.com"></iframe>
Exercise:
Create an iframe with a URL address that goes to
https://www.w3schools.com.
<iframe ="https://www.w3schools.com"></iframe>
HTML JavaScri
pt
JavaScript makes HTML pages more dynamic and interactive.
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
A Taste of JavaScript
Here are some examples of what JavaScript can do:
Example
Example
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
Example
document.getElementById("image").src = "picture.gif";
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
Exercise:
Use JavaScript to change the HTML content of the <p> element to "Hello
World!".
<body>
<p id="demo">Hi.</p>
<script>
document.("demo").innerHTML = "Hello World!";
</script>
</body>
Web pages
Images
Style sheets
JavaScripts
Example
In the following example, the file path points to a file in the images folder
located at the root of the current web:
Example
In the following example, the file path points to a file in the images folder
located in the current folder:
Example
Example
<img src="../images/picture.jpg" alt="Mountain">
Best Practice
It is best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your
current base URL. All links will work on your own computer (localhost) as
well as on your current public domain and your future public domains.
Responsive Web
Design - Introduction
What is Responsive Web Design?
Responsive web design makes your web page look good on all devices.
Web pages should not leave out information to fit smaller devices, but
rather adapt its content to fit any device:
It is called responsive web design when you use CSS and HTML to resize,
hide, shrink, enlarge, or move the content to make it look good on any
screen.
Don't worry if you don't understand the example below, we will break
down the code, step-by-step, in the next chapters:
<!DOCTYPE html>
<html>
<head>
<style>
*{
box-sizing: border-box;
.row::after {
content: "";
clear: both;
display: table;
[class*="col-"] {
float: left;
padding: 15px;
html {
.header {
background-color: #9933cc;
color: #ffffff;
padding: 15px;
.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #33b5e5;
color: #ffffff;
.menu li:hover {
background-color: #0099cc;
}
.aside {
background-color: #33b5e5;
padding: 15px;
color: #ffffff;
text-align: center;
font-size: 14px;
.footer {
background-color: #0099cc;
color: #ffffff;
text-align: center;
font-size: 12px;
padding: 15px;
[class*="col-"] {
width: 100%;
/* For tablets: */
/* For desktop: */
}
</style>
</head>
<body>
<div class="header">
<h1>Chania</h1>
</div>
<div class="row">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>
<h1>The City</h1>
</div>
<div class="aside">
<h2>What?</h2>
<h2>Where?</h2>
<h2>How?</h2>
</div>
</div>
</div>
<div class="footer">
<p>Resize the browser window to see how the content respond to the
resizing.</p>
</div>
</body>
</html>
Responsive Web
Design - The Viewport
What is The Viewport?
The viewport is the user's visible area of a web page.
The viewport varies with the device, and will be smaller on a mobile
phone than on a computer screen.
Before tablets and mobile phones, web pages were designed only for
computer screens, and it was common for web pages to have a static
design and a fixed size.
Then, when we started surfing the internet using tablets and mobile
phones, fixed size web pages were too large to fit the viewport. To fix
this, browsers on those devices scaled down the entire web page to fit
the screen.
You should include the following <meta> viewport element in all your web
pages:
The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is
first loaded by the browser.
So, if the user is forced to scroll horizontally, or zoom out, to see the
whole web page it results in a poor user experience.
3. Use CSS media queries to apply different styling for small and
large screens - Setting large absolute CSS widths for page elements will
cause the element to be too wide for the viewport on a smaller device.
Instead, consider using relative width values, such as width: 100%. Also,
be careful of using large absolute positioning values. It may cause the
element to fall outside the viewport on small devices.
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background-color: lightgreen;
}
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
</style>
</head>
<body>
<p>Resize the browser window. When the width of this document is 600 pixels or
less, the background-color is "lightblue", otherwise it is "lightgreen".</p>
</body>
</html>
Add a Breakpoint
Earlier in this tutorial we made a web page with rows and columns, and it
was responsive, but it did not look good on a small screen.
Media queries can help with that. We can add a breakpoint where certain
parts of the design will behave differently on each side of the breakpoint.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Common CSS for all screen sizes */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: #fff;
text-align: center;
padding: 20px;
}
section {
padding: 20px;
display: flex;
flex-wrap: wrap;
}
aside {
background-color: #f0f0f0;
padding: 10px;
float: left;
width: 30%;
}
aside ul {
list-style-type: none;
padding: 0;
display: flex;
justify-content: space-between;
}
aside li {
margin-bottom: 10px;
}
main {
float: left;
width: 70%;
}
JavaScript Fu
nctions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Example
<p id="demo"></p>
<script>
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
You will learn a lot more about function invocation later in this lesson.
Function Return
When JavaScript reaches a return statement, the function will stop
executing.
Example
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different
results.
The () Operator
The () operator invokes (calls) the function:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius;
Note
As you see from the examples above, toCelsius refers to the function object,
and toCelsius() refers to the function result.
Example
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
Local Variables
Variables declared within a JavaScript function, become LOCAL to the
function.
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
Since local variables are only recognized inside their functions, variables
with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
Exercise:
Execute the function named myFunction.
function myFunction() {
alert("Hello World!");
};
Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions.
The if Statement
Use the if statement to specify a block of JavaScript code to be executed
if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a
JavaScript error.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
</body>
</html>
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time
is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
Exercise:
Fix the if statement to alert "Hello World" if x is greater than y.
if x > y
alert("Hello World");
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
The getDay() method returns the weekday as a number between 0 and 6.
This example uses the weekday number to calculate the weekday name:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
The result of day will be:
Thursday
It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not
match the case.
Example
If today is neither Saturday (6) nor Sunday (0), write a default message:
Example
If default is not the last case in the switch block, remember to end the default
case with a break.
In this example case 4 and 5 share the same code block, and 0 and 6
share another code block:
Example
Strict Comparison
Switch cases use strict comparison (===).
A strict comparison can only be true if the operands are of the same type.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Exercise:
Create a switch statement that will alert "Hello" if fruits is "banana", and
"Welcome" if fruits is "apple".
_____(fruits) {
___ "Banana":
alert("Hello")
break;
___"Apple":
alert("Welcome")
break;
}
JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.
Instead of writing:
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text = "";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Expression 2 defines the condition for the loop to run (i must be less than
5).
Expression 3 increases a value (i++) each time the code block in the loop
has been executed.
Expression 1
Normally you will use expression 1 to initialize the variable used in the
loop (let i = 0).
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i, len, text;
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
And you can omit expression 1 (like when your values are set before the
loop starts):
Example
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Expression 2
Often expression 2 is used to evaluate the condition of the initial variable.
This is not always the case. JavaScript doesn't care. Expression 2 is also
optional.
If expression 2 returns true, the loop will start over again. If it returns
false, the loop will end.
If you omit expression 2, you must provide a break inside the loop. Otherwise
the loop will never end. This will crash your browser. Read about breaks in a
later chapter of this tutorial.
Expression 3
Often expression 3 increments the value of the initial variable.
This is not always the case. JavaScript doesn't care. Expression 3 is
optional.
Expression 3 can also be omitted (like when you increment your values
inside the loop):
Example
let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
Loop Scope
Using var in a loop:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript var</h2>
<p id="demo"></p>
<script>
var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
document.getElementById("demo").innerHTML = i;
</script>
</body>
</html>
Using let in a loop:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript let</h2>
<p id="demo"></p>
<script>
let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
document.getElementById("demo").innerHTML = i;
</script>
</body>
</html>
In the first example, using var, the variable declared in the loop
redeclares the variable outside the loop.
In the second example, using let, the variable declared in the loop does
not redeclare the variable outside the loop.
When let is used to declare the i variable in a loop, the i variable will
only be visible within the loop.
The for/in loop and the for/of loop are explained in the next chapter.
While Loops
The while loop and the do/while are explained in the next chapters.
Exercise:
Create a loop that runs from 0 to 9.
JavaScript For In
The For In Loop
The JavaScript for in statement loops through the properties of an Object:
Syntax
Example
Example Explained
The for in loop iterates over a person object
Each iteration returns a key (x)
The key is used to access the value of the key
The value of the key is person[x]
Example
It is better to use a for loop, a for of loop, or Array.forEach() when the order
is important.
Array.forEach()
The forEach() method calls a function (a callback function) once for each
array element.
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
</body>
</html>
The example above uses only the value parameter. It can be rewritten to:
Example
function myFunction(value) {
txt += value;
}
JavaScript For Of
The For Of Loop
The JavaScript for of statement loops through the values of an iterable
object.
It lets you loop over iterable data structures such as Arrays, Strings,
Maps, NodeLists, and more:
Syntax
variable - For every iteration the value of the next property is assigned
to the variable. Variable can be declared with const, let, or var.
Example
Syntax
while (condition) {
// code block to be executed
}
Example
In the following example, the code in the loop will run, over and over
again, as long as a variable (i) is less than 10:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
If you forget to increase the variable used in the condition, the loop will
never end. This will crash your browser.
Syntax
do {
// code block to be executed
}
while (condition);
Example
The example below uses a do while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Example
for (;cars[i];) {
text += cars[i];
i++;
}
The loop in this example uses a while loop to collect the car names from
the cars array:
Example
while (cars[i]) {
text += cars[i];
i++;
}
Exercise:
Create a loop that runs as long as i is less than 10.
*Week 8:*
HTML Entities
Reserved characters in HTML must be replaced with entities:
< (less than) = <
> (greather than) = >
If you use the less than (<) or greater than (>) signs in your HTML text,
the browser might mix them with tags.
&entity_name;
&#entity_number;
Non-breaking Space
A commonly used HTML entity is the non-breaking space:
A non-breaking space is a space that will not break into a new line.
§ 10
10 km/h
10 PM
If you write 10 spaces in your text, the browser will remove 9 of them.
To add real spaces to your text, you can use the character entity.
Note
HTML Symbols
Symbols or letters that are not present on your keyboard can be added to
HTML using entities.
To add such symbols to an HTML page, you can use the entity name or
the entity number (a decimal or a hexadecimal reference) for the symbol:
Example
I will display €
I will display €
I will display €
Most people enter the name when surfing, because names are easier to remember
than numbers.
A Uniform Resource Locator (URL) is used to address a document (or other data) on the web.
scheme://prefix.domain:port/path/filename
Explanation:
scheme - defines the type of Internet service (most common is http or https)
prefix - defines a domain prefix (default for http is www)
domain - defines the Internet domain name (like w3schools.com)
port - defines the port number at the host (default for http is 80)
path - defines a path at the server (If omitted: the root directory of the site)
filename - defines the name of a document or resource
URL Encoding
URLs can only be sent over the Internet using the ASCII character-set. If a URL contains
characters outside the ASCII set, the URL has to be converted.
URL encoding converts non-ASCII characters into a format that can be transmitted over the
Internet.
URL encoding replaces non-ASCII characters with a "%" followed by hexadecimal digits.
URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign,
or %20.
€ %80 %E2%82%AC
£ %A3 %C2%A3
© %A9 %C2%A9
® %AE %C2%AE
À %C0 %C3%80
Á %C1 %C3%81
 %C2 %C3%82
à %C3 %C3%83
Ä %C4 %C3%84
Å %C5 %C3%85
JavaScript HTML DOM
With the HTML DOM, JavaScript can access and change all the elements
of an HTML document.
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
In other words: The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
HTML DOM properties are values (of HTML Elements) that you can set or
change.
A property is a value that you can get or set (like changing the content
of an HTML element).
Example
The following example changes the content (the innerHTML) of
the <p> element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events
An HTML event can be something the browser does, or something a user does.
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
Event Description
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
Exercise:
The <button> element should do something when someone clicks on it. Try to fix it!
If you want to access any element in an HTML page, you always start with accessing the
document object.
Below are some examples of how you can use the document object to access and manipulate
HTML.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
document.applets Deprecated 1
document.baseURI Returns the absolute base URI of the document 3
document.domConfig Obsolete. 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href 1
attribute
To do so, you have to find the elements first. There are several ways to
do this:
Example
If the element is found, the method will return the element as an object
(in element).
Example
This example finds the element with id="main", and then finds
all <p> elements inside "main":
Example
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
Example
const x = document.getElementsByClassName("intro");
Example
const x = document.querySelectorAll("p.intro");
Finding HTML Elements by HTML Object
Collections
This example finds the form element with id="frm1", in the forms
collection, and displays all element values:
Example
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
The following HTML objects (and object collections) are also accessible:
document.anchors
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
document.links
document.scripts
document.title
Exercise:
Use the getElementById method to find the <p> element, and change its
text to "Hello".
Example
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Example explained:
Example
<!DOCTYPE html>
<html>
<body>
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Example explained:
This example changes the value of the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("demo").innerHTML = "Date : " +
Date(); </script>
</body>
</html>
document.write()
In JavaScript, document.write() can be used to write directly to the HTML
output stream:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
Exercise:
Use HTML DOM to change the value of the image's src attribute.
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted:
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the
server.
Client side validation is performed by a web browser, before input is sent to a web server.
Example
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Using Events
The HTML DOM allows you to execute code when an event occurs.
An element is clicked on
The page has loaded
Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when
the user clicks a button:
Example
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Exercise:
Change the text color of the <p> element to "red".
<p id="demo"></p>
<script>
document.getElementById("demo") = "red";
</script>
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element.
onclick=JavaScript
In this example, the content of the <h1> element is changed when a user
clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
Example
<script>
document.getElementById("myBtn").onclick = displayDate;
Example</script>
The onload event can be used to check the visitor's browser type and
browser version, and load the proper version of the web page based on
the information.
The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
You can add many event handlers of the same type to one element, i.e
two "click" events.
You can add event listeners to any DOM object not only HTML elements.
i.e the window object.
Syntax
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown"
or any other HTML DOM Event.)
The second parameter is the function we want to call when the event
occurs.
Note that you don't use the "on" prefix for the event; use "click" instead of
"onclick".
Example
Example
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Example
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Passing Parameters
When passing parameter values, use an "anonymous function" that calls
the specified function with the parameters:
Example
In bubbling the inner most element's event is handled first and then the
outer: the <p> element's click event is handled first, then the <div>
element's click event.
In capturing the outer most element's event is handled first and then the
inner: the <div> element's click event will be handled first, then the <p>
element's click event.
The default value is false, which will use the bubbling propagation, when
the value is set to true, the event uses the capturing propagation.
Example
document.getElementById("myP").addEventListener("click",
myFunction, true);
document.getElementById("myDiv").addEventListener("click",
myFunction, true);
Example
element.removeEventListener("mousemove", myFunction);
Exercise:
Use the eventListener to assign an onclick event to the <button> element.
<button id="demo"></button>
<script>
document.getElementById("demo"). (" ", myFunction);
</script>