CC101 Introduction To Computing HTMLCSS

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 304

COLLEGE OF INFORMATION AND

COMMUNICATION TECHNOLOGY

COMPUTER SCIENCE
DEPARTMENT

Introduction to
Computing
(HTML/CSS)

Online Module: Laboratory Manual


Taguig City University
Gen. Santos Ave., Central Bicutan, Taguig City
INTRODUCTION

Programming, or coding, is like solving a puzzle. Consider a human language, like English or
French. We use these languages to turn thoughts and ideas into actions and behavior. In
programming, the goal of the puzzle is exactly the same - you're just driving different kinds of
behavior, and the source of that behavior isn't a human. It's a computer.

A programming language is our way of communicating with software. The people who use
programming languages are often called programmers or developers. The things we tell
software using a programming language could be to make a webpage look a certain way, or
to make an object on the page move if the human user takes a certain action.

So, when a web designer is given an end goal like "create a webpage that has this header,
this font, these colors, these pictures, and an animated unicorn walking across the screen
when users click on this button," the web designer's job is to take that big idea and break it
apart into tiny pieces, and then translate these pieces into instructions that the computer can
understand - including putting all these instructions in the correct order or syntax.

Every page on the web that you visit is built using a sequence of separate instructions, one
after another. Your browser (Chrome, Firefox, Safari, and so on) is a big actor in translating
code into something we can see on our screens and even interact with. It can be easy to forget
that code without a browser is just a text file -- it's when you put that text file into a browser
that the magic happens. When you open a web page, your browser fetches the HTML and
other programming languages involved and interprets it.

HTML and CSS are actually not technically programming languages; they're just page
structure and style information. But before moving on to JavaScript and other true languages,
you need to know the basics of HTML and CSS, as they are on the front end of every web
page and application.

In the very early 1990s, HTML was the only language available on the web. Web developers
had to painstakingly code static sites, page by page. A lot's changed since then: Now there
are many computer programming languages available which includes HTML5 and CSS.

OVERVIEW
This course introduces students to basic web design using HTML (Hypertext Markup
Language) and CSS (Cascading Style Sheets). The course does not require any prior
knowledge of HTML or web design. Throughout the course students are introduced to planning
and designing effective web pages; implementing web pages by writing HTML and CSS code;
enhancing web pages with the use of page layout techniques, text formatting, graphics,
images, and multimedia; and producing a functional, multi-page website.

OBJECTIVES
At the end of this course, the students should be able to:
➢ Design website using Hypertext Markup Language (HTML) and Cascading Style
Sheet (CSS).
➢ Recognize and identify HTML web page elements
➢ Insert a graphic within a web page.
➢ Create a link within a web page.
➢ Create a table within a web page.
➢ Insert heading levels within a web page.
➢ Insert ordered and unordered lists within a web page.
➢ Apply CSS to format web page elements
➢ Apply effective web design principles.
➢ Enhance web pages using text formatting, color, graphics, images, and multimedia
➢ Incorporate forms into web pages
➢ Plan, design, and publish a multi-page website

PRE-TEST

1. What does HTML stand for?


a. Hyperlinks and Text Markup Language
b. Home Tool Markup Language
c. Hyper Text Markup Language
2. Who is making the Web standards?
a. Google
b. Mozilla
c. The World Wide Web Consortium
d. Microsoft
3. Choose the correct HTML element far the largest heading:
a. <h1>
b. < heading >
c. < head >
d. <h6>
4. What is the correct HTML element for inserting a line break?
a. <br>
b. <break>
c. <lb>
5. What is the correct HTML for adding a background color?
a. <body style=”background-color:yellow;"›
b. <body bg="yellow">
c. <background>yellow</background>
6. Choose the correct HTML element to define important text
a. <b>
b. <i>
c. <important>
d. <strong>
7. Choose the correct HTML element to define emphasized text
a. <italic>
b. <em>
c. <i>
8. What is the correct HTML for creating a hyperlink?
a. <a url="http://www.taguig.gov.ph">Taguig Website</a>
b. <a name=" http://www.taguig.gov.ph ">Taguig Website </a>
c. <a href=" http://www.taguig.gov.ph ">Taguig Website </a>
d. <a> http://www.taguig.gov.ph </a>
9. Which character is used to indicate an end tag?
a. /
b. *
c. <
d. ^
10. How can you open a link in a new tab/browser window?
a. <a href="url" target="new">
b. <a href="url" new>
c. <a href="url" target="_blank">
11. Which of these elements are all <table> elements?
a. <thead> <body> <tr>
b. <table> <tr> <tt>
c. <table> <tr> <td>
d. <table> < head> <tfoot>
12. Inline elements are normally displayed without starting a new line.
a. True
b. False
13. How can you make a numbered list?
a. <dl>
b. <list>
c. <ol>
d. <ul>
14. How can you make a bulleted list?
a. <dl>
b. <ol>
c. <list>
d. <ul>
15. What is the correct HTML for making a checkbox?
a. <input type="check”>
b. <checkbox>
c. <check>
d. <input type="checkbox''>
16. What is the correct HTML for making a text input field?
a. <textinput type="text”>
b. <input type="text">
c. <textfield >
d. <input type="textfield">
17. What is the correct HTML for making a drop-down list?
a. <input type="dropdown">
b. <list>
c. <select>
d. <input type="list">
18. What is the correct HTML for making a text area?
a. <input type="textarea">
b. <input type="textbox">
c. <textarea>
19. What is the correct HTML for inserting an image?
a. <img src="image.gif" alt="Mylmage">
b. <image src="image.gif” alt="Mylmage">
c. <img href="image.gif' alt="Mylmage">
d. <img alt="Mylmage">image.gif</img>
20. What is the correct HTML for inserting a background image?
a. <background img="background.gif”>
b. <body style="background-image:url(background.gif)">
c. <body bg="background.gif”>
21. An <iframe> is used to display a web page within a web page.
a. True
b. False
c. There is no such thing as an <iframe>
22. HTML comments start with <!-- and end with -->
a. True
b. False
23. Block elements are normally displayed without starting a new line.
a. True
b. False
24. Which HTML element defines the title of a document?
a. <title>
b. <head>
c. <meta>
25. Which HTML attribute specifies an alternate text for an image, if the image cannot be
displayed?
a. alt
b. src
c. title
d. longdesc
26. Which doctype is correct for HTML5?
a. <IDOCTYPE html>
b. <IDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5.0//EN" "
http://www.w3.org/TR/htm15/strict.dtd" >
c. <IDOCTYPE HTMLS>
27. Which HTML element is used to specify a footer for a document or section?
a. <section>
b. <bottom>
c. <footer>
28. In HTML, you can embed SVG elements directly into an HTML page.
a. True
b. False
29. What is the correct HTML element for playing video files?
a. <media>
b. <movie>
c. <video>
30. What is the correct HTML element for playing audio files?
a. <mp3>
b. <sound>
c. <audio>
31. The HTML global attribute, "contenteditable" is used to:
a. Specify whether the content of an element should be editable or not
b. Specifies a context menu for an element.
c. The menu appears when a user right-clicks on the element Update content
from the server
d. Return the position of the first found occurrence of content inside a string
32. In HTML, onblur and onfocus are:
a. Style attributes
b. Event attributes
c. HTML elements
33. Graphics defined by SVG is in which format?
a. HTML
b. XML
c. CSS
34. The HTML <canvas> element is used to:
a. draw graphics
b. display database records
c. manipulate data in MySQL
d. create draggable elements
35. In HTML, which attribute is used to specify that an input field must be filled out?
a. required
b. formvalidate
c. placeholder
d. validate
36. Which input type defines a slider control?
a. search
b. slider
c. range
d. controls
37. Which HTML element is used to display a scalar measurement within a range?
a. <range>
b. <gauge>
c. <meter>
d. <measure>
38. Which HTML element defines navigation links?
a. <navigation>
b. <navigate>
c. <nav>
39. In HTML, what does the <aside> element define?
a. A navigation list to be shown at the left side of the page
b. The ASCII character-set; to send information between computers on the
Internet
c. Content aside from the page content
40. Which HTML element is used to specify a header for a document or section?
a. <top>
b. <header>
c. <head>
d. <section>
41. What does CSS stand for?
a. Colorful Style Sheets
b. Cascading Style Sheets
c. Creative Style Sheets
d. Computer Style Sheets
42. What is the correct HTML for referring to an external style sheet?
a. <style src="mystyle.css">
b. <link rel="stylesheet" type="text/css" href="mystyle.css">
c. <stylesheet>mystyle.css</stylesheet>
43. Where in an HTML document is the correct place to refer to an external style sheet?
a. In the <body> section
b. At the end of the document
c. In the <head> section
44. Which HTML tag is used to define an internal style sheet?
a. <css>
b. <script>
c. <style>
45. Which HTML attribute is used to define inline styles?
a. class
b. style
c. font
d. styles
46. Which is the correct CSS syntax?
a. {body;color:black;}
b. body {color: black;}
c. {body:color=black;}
d. body:color=black;
47. How do you insert a comment in a CSS file?
a. /* this is a comment */
b. ' this is a comment
c. // this is a comment //
d. // this is a comment
48. Which property is used to change the background color?
a. bgcolor
b. color
c. background-color
49. How do you add a background color for all <h1> elements?
a. all.h1 {background-color:#FFFFFF;}
b. h1 {background-color:#FFFFFF;}
c. h1.all {background-color:#FFFFFF;}
50. Which CSS property is used to change the text color of an element?
a. color
b. fgcolor
c. text-color
51. Which CSS property controls the text size?
a. font-size
b. text-size
c. text-style
d. font-style
52. What is the correct CSS syntax for making all the <p> elements bold?
a. <p style="text-size:bold;">
b. p {font-weight:bold;}
c. <p style="font-size:bold;">
d. p {text-size:bold;}
53. How do you display hyperlinks without an underline?
a. a {decoration:no-underline;}
b. a {text-decoration:none;}
c. a {text-decoration:no-underline;}
d. a {underline:none;}
54. How do you make each word in a text start with a capital letter?
a. transform:capitalize
b. text-transform:capitalize
c. You can't do that with CSS
d. text-style:capitalize
55. Which property is used to change the font of an element?
a. font-style
b. font-weight
c. font-family
56. How do you make the text bold?
a. font-weight:bold;
b. style:bold;
c. font:bold;
57. How do you display a border like this:
The top border = 10 pixels
The bottom border = 5 pixels
The left border = 20 pixels
The right border = 1pixel?
a. border-width:10px 1px 5px 20px;
b. border-width:10px 20px 5px 1px;
c. border-width:10px 5px 20px 1px;
d. border-width:5px 20px 10px 1px;
58. Which property is used to change the left margin of an element?
a. margin-left
b. indent
c. padding-left
59. When using the padding property; are you allowed to use negative values?
a. No
b. Yes
60. How do you make a list that lists its items with squares?
a. list: square;
b. list-type: square;
c. list-style-type: square;
61. How do you select an element with id 'demo'?
a. .demo
b. *demo
c. demo
d. #demo
62. How do you select elements with class name 'test'?
a. .test
b. test
c. *test
d. #test
63. How do you select all p elements inside a div element?
a. div p
b. div + p
c. div.p
64. How do you group selectors?
a. Separate each selector with a plus sign
b. Separate each selector with a space
c. Separate each selector with a comma
65. What is the default value of the position property?
a. absolute
b. relative
c. static
d. fixed
MODULE 1 – INTRODUCTION TO COMPUTING

LESSON 1

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Define HTML.
➢ Use editor to create a simple HTML document.
➢ Enumerate the different HTML elements.

HTML Introduction
HTML is the standard markup language for creating Web pages.

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.

A Simple HTML Document

Example

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

What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:

<tagname>Content goes here...</tagname>

The HTML element is everything from the start tag to the end tag:

<h1>My First Heading</h1>


<p>My first paragraph.</p>

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!

Web Browsers

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents
and display them correctly.

A browser does not display the HTML tags, but uses them to determine how to display the
document:
HTML Page Structure

Below is a visualization of an HTML page structure:

Note: Only the content inside the <body> section (the white area above) will be displayed in
a browser.

HTML History

Since the early days of the World Wide Web, there have been many versions of HTML:
HTML Editors

A simple text editor is all you need to learn HTML.

Learn HTML Using Notepad or TextEdit

Web pages can be created and modified by using professional HTML editors.

However, for learning HTML we recommend a simple text editor like Notepad (PC) or
TextEdit (Mac).

We believe in that using a simple text editor is a good way to learn HTML.

Follow the steps below to create your first web page with Notepad or TextEdit.

Step 1: Open Notepad (PC)

Windows 8 or later:

Open the Start Screen (the window symbol at the bottom left on your screen). Type Notepad.

Windows 7 or earlier:

Open Start > Programs > Accessories > Notepad

Step 2: Write Some HTML

Write or copy the following HTML code into Notepad:


Step 3: Save the HTML Page

Save the file on your computer. Select File > Save as in the Notepad menu.

Name the file "index.htm" and set the encoding to UTF-8 (which is the preferred encoding for
HTML files).

Tip: You can use either .htm or .html as file extension. There is no difference, it is up to you.

Step 4: View the HTML Page in Your Browser

Open the saved HTML file in your favorite browser (double click on the file, or right-click -
and choose "Open with").

The result will look


much like this:
HTML Basic Examples

HTML Documents

All HTML documents must start with a document type declaration: <!DOCTYPE html>.

The HTML document itself begins with <html> and ends with </html>.

The visible part of the HTML document is between <body> and </body>.

Example

The <!DOCTYPE> Declaration

The <!DOCTYPE> declaration represents the document type, and helps browsers to display
web pages correctly.

It must only appear once, at the top of the page (before any HTML tags).

The <!DOCTYPE> declaration is not case sensitive.

The <!DOCTYPE> declaration for HTML5 is:

<!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:
Sample Code:

Output:
HTML Paragraphs

HTML paragraphs are defined with the <p> tag:

Sample Code:

Output

HTML Links

HTML links are defined with the <a> tag:

Sample Code:
Output:

The link's destination is specified in the href attribute.

Attributes are used to provide additional information about HTML elements.

HTML Images

HTML images are defined with the <img> tag.

The source file (src), alternative text (alt), width, and height are provided as attributes:

Sample Code:

Output:
How to View HTML Source?

Have you ever seen a Web page and wondered "Hey! How did they do that?"

View HTML Source Code:

Right-click in an HTML page and select "View Page Source" (in Chrome) or "View Source"
(in Edge), or similar in other browsers. This will open a window containing the HTML source
code of the page.

Inspect an HTML Element:

Right-click on an element (or a blank area), and choose "Inspect" or "Inspect Element" to
see what elements are made up of (you will see both the HTML and the CSS). You can also
edit the HTML or CSS on-the-fly in the Elements or Styles panel that opens.

HTML Elements

An HTML element is defined by a start tag, some content, and an end tag.

HTML Elements

An HTML element is defined by a start tag, some content, and an end tag:

<tagname>Content goes here...</tagname>

The HTML element is everything from the start tag to the end tag:

<h1>My First Heading</h1>


<p>My first paragraph.</p>

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

Nested HTML Elements

HTML elements can be nested (this means that elements can contain other elements).

All HTML documents consist of nested HTML elements.


The following example contains four HTML elements (<html>, <body>, <h1> and <p>):

Sample Code:

Output:

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>.

Then, inside the <html> element there is a <body> element:

<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
The <body> element defines the document's body.

It has a start tag <body> and an end tag </body>.

Then, inside the <body> element there is two other elements: <h1> and <p>:

<h1>My First Heading</h1>


<p>My first paragraph.</p>

The <h1> element defines a heading.

It has a start tag <h1> and an end tag </h1>:

<h1>My First Heading</h1>

The <p> element defines a paragraph.

It has a start tag <p> and an end tag </p>:

<p>My first paragraph.</p>

Never Skip the End Tag

Some HTML elements will display correctly, even if you forget the end tag:

Sample Code:

Output:
However, never rely on this! Unexpected results and errors may occur if you forget the end
tag!

Empty HTML Elements

HTML elements with no content are called empty elements.

The <br> tag defines a line break, and is an empty element without a closing tag:

Sample Code:

Output:

HTML is Not Case Sensitive

HTML tags are not case sensitive: <P> means the same as <p>.

The HTML standard does not require lowercase tags, but W3C recommends lowercase in
HTML, and demands lowercase for stricter document types like XHTML.
LESSON 2

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Enumerate and explain the attributes of the different HTML elements.
➢ Create a web page using HTML headings.
➢ Use HTML paragraphs tag in designing web page.
➢ Develop web page using different HTML styles.

HTML 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"

The href Attribute

The <a> tag defines a hyperlink. The href attribute specifies the URL of the page the link
goes to:

Sample Code:

Output:
The src Attribute

The <img> tag is used to embed an image in an HTML page. The src attribute specifies the
path to the image to be displayed:

Sample Code:

Output:

The width and height Attributes

The <img> tag should also contain the width and height attributes, which specifies the width
and height of the image (in pixels):

Example
<img src="img_girl.jpg" width="500" height="600">
The alt Attribute

The required alt attribute for the <img> tag specifies an alternate text for an image, if the
image for some reason cannot be displayed. This can be due to slow connection, or an error
in the src attribute, or if the user uses a screen reader.

Example
<img src="img_girl.jpg" alt="Girl with a jacket">

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">

HTML Headings

HTML headings are titles or subtitles that you want to display on a webpage.

Example

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: Browsers automatically add some white space (a margin) before and after a heading.

Headings Are Important

Search engines use the headings to index the structure and content of your web pages.

Users often skim a page by its headings. It is important to use headings to show the
document structure.

<h1> headings should be used for main headings, followed by <h2> headings, then the less
important <h3>, and so on.

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
<h1 style="font-size:60px;">Heading 1</h1>

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.

A paragraph always starts on a new line, and browsers automatically add some white space
(a margin) before and after 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>

HTML Horizontal Rules

The <hr> tag defines a thematic break in an HTML page, and is most often displayed as a
horizontal rule.

The <hr> element is used to separate content (or define a change) in an HTML page:

Example
<h1>This is heading 1</h1>
<p>This is some text.</p>
<hr>
<h2>This is heading 2</h2>
<p>This is some other text.</p>
<hr>

The <hr> tag is an empty tag, which means that it has no end tag.

HTML Line Breaks

The HTML <br> element defines a line break.

Use <br> if you want a line break (a new line) without starting a new paragraph:

Example
<p>This is<br>a paragraph<br>with line breaks.</p>

The <br> tag is an empty tag, which means that it has no end tag.
The Poem Problem

This poem will display on a single line:

Example
<p>
My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</p>

Solution - The HTML <pre> Element

The HTML <pre> element defines preformatted text.

The text inside a <pre> element is displayed in a fixed-width font (usually Courier), and it
preserves both spaces and line breaks:

Example
<pre>
My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</pre>

The HTML style attribute is used to add styles to an element, such as color, font, size, and
more.

Example
The HTML Style Attribute

Setting the style of an HTML element, can be done with the style attribute.

The HTML style attribute has the following syntax:

<tagname style="property:value;">

The property is a CSS property. The value is a CSS value.

You will learn more about CSS later in this tutorial.

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:

<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>

<h1 style="background-color:powderblue;">This is a heading</h1>


<p style="background-color:tomato;">This is a paragraph.</p>

</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>

HTML Text Formatting

HTML contains several elements for defining text with a special meaning.
LESSON 3

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Create a web page using HTML formatting.
➢ Use HTML quotations tag in designing web page.
➢ Develop web page using HTML colors.
➢ Utilize HTML comments in documenting HTML source code.

HTML Formatting Elements

Formatting elements were designed to display special types of text:

• <b> - Bold text


• <strong> - Important text
• <i> - Italic text
• <em> - Emphasized text
• <mark> - Marked text
• <small> - Smaller text
• <del> - Deleted text
• <ins> - Inserted text
• <sub> - Subscript text
• <sup> - Superscript text

HTML <b> and <strong> Elements

The HTML <b> element defines bold text, without any extra importance.

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
<i>This text is italic</i>

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
<em>This text is emphasized</em>

HTML <small> Element

The HTML <small> element defines smaller text:

Example
<small>This is some smaller text.</small>

HTML <mark> Element

The HTML <mark> element defines text that should be marked or highlighted:

Example
<p>Do not forget to buy <mark>milk</mark> today.</p>

HTML <del> Element

The HTML <del> element defines text that has been deleted from a document. Browsers will
usually strike a line through deleted text:

Example
<p>My favorite color is <del>blue</del> red.</p>

HTML <ins> Element

The HTML <ins> element defines a text that has been inserted into a document. Browsers
will usually underline inserted text:

Example
<p>My favorite color is <del>blue</del> <ins>red</ins>.</p>

HTML <sub> Element

The HTML <sub> element defines subscript text. Subscript text appears half a character
below the normal line, and is sometimes rendered in a smaller font. Subscript text can be
used for chemical formulas, like H2O:

Example
<p>This is <sub>subscripted</sub> text.</p>
HTML <sup> Element

The HTML <sup> element defines superscript text. Superscript text appears half a character
above the normal line, and is sometimes rendered in a smaller font. Superscript text can be
used for footnotes, like WWW[1]:

Example
<p>This is <sup>superscripted</sup> text.</p>

HTML Quotation and Citation Elements

In this chapter we will go through the <blockquote>,<q>, <abbr>, <address>, <cite>,


and <bdo> HTML elements.

HTML <blockquote> for Quotations

The HTML <blockquote> element defines a section that is quoted from another source.

Browsers usually indent <blockquote> elements.

Example
<p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.
</blockquote>

HTML <q> for Short Quotations

The HTML <q> tag defines a short quotation.

Browsers normally insert quotation marks around the quotation.

Example
<p>WWF's goal is to: <q>Build a future where people live in harmony with
nature.</q></p>

HTML <abbr> for Abbreviations

The HTML <abbr> tag defines an abbreviation or an acronym, like "HTML", "CSS", "Mr.",
"Dr.", "ASAP", "ATM".

Marking abbreviations can give useful information to browsers, translation systems and
search-engines.
Tip: Use the global title attribute to show the description for the abbreviation/acronym when
you mouse over the element.

Example
<p>The <abbr title="World Health Organization">WHO</abbr> was founded in
1948.</p>

HTML <address> for Contact Information

The HTML <address> tag defines the contact information for the author/owner of a
document or an article.

The contact information can be an email address, URL, physical address, phone number,
social media handle, etc.

The text in the <address> element usually renders in italic, and browsers will always add a
line break before and after the <address> element.

Example
<address>
Written by John Doe.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>

HTML <cite> for Work Title

The HTML <cite> tag defines the title of a creative work (e.g. a book, a poem, a song, a
movie, a painting, a sculpture, etc.).

Note: A person's name is not the title of a work.

The text in the <cite> element usually renders in italic.

Example
<p><cite>The Scream</cite> by Edvard Munch. Painted in 1893.</p>

HTML <bdo> for Bi-Directional Override

BDO stands for Bi-Directional Override.

The HTML <bdo> tag is used to override the current text direction:

Example
<bdo dir="rtl">This text will be written from right to left</bdo>
HTML Comments

HTML comments are not displayed in the browser, but they can help document your HTML
source code.

HTML Comment Tags

You can add comments to your HTML source by using the following syntax:

<!-- Write your comments here -->

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.

With comments you can place notifications and reminders in your HTML code:

Example
<!-- This is a comment -->

<p>This is a paragraph.</p>

<!-- Remember to add more information here -->

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
<!-- Do not display this image at the moment
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->

HTML Colors

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA
values.

Color Names

In HTML, a color can be specified by using a color name:


Example

Background Color

You can set the background color for HTML elements:

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.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.

Example

Border Color

You can set the color of borders:


Example

Color Values

In HTML, colors can also be specified using RGB values, HEX values, HSL values, RGBA
values, and HSLA values:

Same as color name "Tomato":

Same as color name "Tomato", but 50% transparent:


Example

RGB Colors

RGB Value

In HTML, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)

Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255)
and the others are set to 0.

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).

Example
Shades of gray are often defined using equal values for all the 3 light sources:

Example

RGBA Value

RGBA color values are an extension of RGB color values with an alpha channel - which
specifies the opacity for a color.

An RGBA color value is specified with:

rgba(red, green, blue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at
all):
Example

CSS HEX Colors

HEX Value

In HTML, a color can be specified using a hexadecimal value in the form:

#rrggbb

Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as
decimal 0-255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the
others are set to the lowest value (00).
Example:

Shades of gray are often defined using equal values for all the 3 light sources:
CSS HSL Colors

HSL Value

In HTML, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)

Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white

Example:

Saturation

Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray

50% is 50% gray, but you can still see the color.
0% is completely gray, you can no longer see the color.

Example:

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) 100% means
full lightness (white).

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the
lightness from 0% to 100% to get darker/lighter shades:

Example:
HSLA Value

HSLA color values are an extension of HSL color values with an alpha channel - which
specifies the opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at
all):

HTML Links

Links are found in nearly all web pages. Links allow users to click their way from page to
page.
LESSON 4

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Use HTML hyperlink tag to create clickable links in web page.
➢ Develop web page with images.
➢ Create tables using HTML.

HTML Links - Hyperlinks

HTML links are hyperlinks.

You can click on a link and jump to another document.

When you move the mouse over a link, the mouse arrow will turn into a little hand.

Note: A link does not have to be text. A link can be an image or any other HTML element!

HTML Links - Syntax

The HTML <a> tag defines a hyperlink. It has the following syntax:

<a href="url">link text</a>

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

This example shows how to create a link to W3Schools.com:

<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>

By default, links will appear as follows in all browsers:

• An unvisited link is underlined and blue


• A visited link is underlined and purple
• An active link is underlined and red

Tip: Links can of course be styled with CSS, to get another look!
HTML Links - The target Attribute

By default, the linked page will be displayed in the current browser window. To change this,
you must specify another target for the link.

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

• _self - Default. Opens the document in the same window/tab as it was clicked
• _blank - Opens the document in a new window or tab
• _parent - Opens the document in the parent frame
• _top - Opens the document in the full body of the window

Example

Use target="_blank" to open the linked document in a new browser window or tab:

<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

Absolute URLs vs. Relative URLs

Both examples above are using an absolute URL (a full web address) in the href attribute.

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>

HTML Links - Use an Image as a Link

To use an image as a link, just 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>

Link to an Email Address

Use mailto: inside the href attribute to create a link that opens the user's email program (to
let them send a new email):

Example
<a href="mailto:someone@example.com">Send email</a>

Button as a Link

To use an HTML button as a link, you have to add some JavaScript code.

JavaScript allows you to specify what happens at certain events, such as a click of a button:

Example
<button onclick="document.location='default.asp'">HTML Tutorial</button>

Tip: Learn more about JavaScript in our JavaScript Tutorial.

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
<a href="https://www.w3schools.com/html/" title="Go to W3Schools HTML
section">Visit our HTML Tutorial</a>

More on Absolute URLs and Relative URLs

Example

Use a full URL to link to a web page:

<a href="https://www.w3schools.com/html/default.asp">HTML tutorial</a>

Example

Link to a page located in the html folder on the current web site:

<a href="/html/default.asp">HTML tutorial</a>

Example

Link to a page located in the same folder as the current page:

<a href="default.asp">HTML tutorial</a>

HTML Images

Images can improve the design and the appearance of a web page.

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">

HTML Images Syntax

The HTML <img> tag is used to embed an image in a web page.

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.

The <img> tag has two required attributes:

• src - Specifies the path to the image


• alt - Specifies an alternate text for the image

Syntax
<img src="url" alt="alternatetext">

The src Attribute

The required src attribute specifies the path (URL) to the image.

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 stay in
the same spot in relation to the web page, otherwise your visitors will get a broken link icon.
The broken link icon is shown if the browser cannot find the image.

The alt Attribute

The required alt attribute provides an alternate text for an image, if the user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user uses a
screen reader).

The value of the alt attribute should describe the image:

Example
<img src="img_chania.jpg" alt="Flowers in Chania">

If a browser cannot find an image, it will display the value of the alt attribute:

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.

Image Size - Width and Height

You can use the style attribute to specify the width and height of an image.

Example

Alternatively, you can use the width and height attributes:

Example
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

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.

Width and Height, or Style?

The width, height, and style attributes are all valid in HTML.

However, we suggest using the style attribute. It prevents styles sheets from changing the
size of images:

Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 100%;
}
</style>
</head>
<body>

<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">

<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

</body>
</html>

Images in Another Folder


If you have your images in a sub-folder, you must include the folder name in the src attribute:

Example
<img src="/images/html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

Images on Another Server

Some web sites store their images on another server.

Actually, you can access images from any web address in the world:

Example
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools
.com">
Animated Images

HTML allows animated GIFs:

Example
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">

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
<p><img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>

<p><img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">


The image will float to the left of the text.</p>

HTML Image Maps

With HTML image maps, you can create clickable areas on an image.
Image Maps

The HTML <map> tag defines an image map. An image map is an image with clickable
areas. The areas are defined with one or more <area> tags.

Example

Here is the HTML source code for the image map above:

<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>

How Does it Work?

The idea behind an image map is that you should be able to perform different actions
depending on where in the image you click.

To create an image map you need an image, and some HTML code that describes the
clickable areas.

The Image

The image is inserted using the <img> tag. The only difference from other images is that you
must add a usemap attribute:

<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

The usemap value starts with a hash tag # followed by the name of the image map, and is
used to create a relationship between the image and the image map.

Tip: You can use any image as an image map!

Create Image Map

Then, add a <map> element.

The <map> element is used to create an image map, and is linked to the image by using the
required name attribute:
<map name="workmap">

The name attribute must have the same value as the <img>'s usemap attribute .

The Areas

Then, add the clickable areas.

A clickable area is defined using an <area> element.

Shape

You must define the shape of the clickable area, and you can choose one of these values:

• rect - defines a rectangular region


• circle - defines a circular region
• poly - defines a polygonal region
• default - defines the entire region

You must also define some coordinates to be able to place the clickable area onto the
image.

Shape="rect"

The coordinates for shape="rect" come in pairs, one for the x-axis and one for the y-axis.

So, the coordinates 34,44 is located 34 pixels from the left margin and 44 pixels from the top:

The coordinates 270,350 is located 270 pixels from the left margin and 350 pixels from the
top:

Now we have enough data to create a clickable rectangular area:

Example
<area shape="rect" coords="34, 44, 270, 350" href="computer.htm">

This is the area that becomes clickable and will send the user to the page "computer.htm":

Shape="circle"

To add a circle area, first locate the coordinates of the center of the circle:
337,300

Then specify the radius of the circle:

44 pixels

Now you have enough data to create a clickable circular area:

Example
<area shape="circle" coords="337, 300, 44" href="coffee.htm">

This is the area that becomes clickable and will send the user to the page "coffee.htm":

Shape="poly"

The shape="poly" contains several coordinate points, which creates a shape formed with
straight lines (a polygon).

This can be used to create any shape.

Like maybe a croissant shape!

How can we make the croissant in the image below become a clickable link?

We have to find the x and y coordinates for all edges of the croissant:
The coordinates come in pairs, one for the x-axis and one for the y-axis:

Example
<area shape="poly" coords="140,121,181,116,204,160,204,222,191,270,140,329,85,
355,58,352,37,322,40,259,103,161,128,147" href="croissant.htm">

This is the area that becomes clickable and will send the user to the page "croissant.htm":

Image Map and JavaScript

A clickable area can also trigger a JavaScript function.

Add a click event to the <area> element to execute a JavaScript function:

Example

Here, we use the onclick attribute to execute a JavaScript function when the area is clicked:

<map name="workmap">
<area shape="circle" coords="337,300,44" onclick="myFunction()">
</map>

<script>
function myFunction() {
alert("You clicked the coffee cup!");
}
</script>

HTML <picture> Element

The HTML <picture> element allows us to display different pictures for different devices or
screen sizes.

The HTML <picture> Element

The HTML <picture> element gives web developers more flexibility in specifying image
resources.

The <picture> element contains one or more <source> elements, each referring to different
images through the srcset attribute. This way the browser can choose the image that best
fits the current view and/or device.

Each <source> element has a media attribute that defines when the image is the most
suitable.

Example

Show different images for different screen sizes:

<picture>
<source media="(min-width: 650px)" srcset="img_food.jpg">
<source media="(min-width: 465px)" srcset="img_car.jpg">
<img src="img_girl.jpg">
</picture>
Note: Always specify an <img> element as the last child element of the <picture> element.
The <img> element is used by browsers that do not support the <picture> element, or if none
of the <source> tags matches.

When to use the Picture Element

There are two main purposes for the <picture> element:

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

The browser will use the first image format it recognizes:

<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 Tables

HTML tables allow web developers to arrange data into rows and columns.

Example

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Centro comercial Moctezuma Francisco Chang Mexico


Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Define an HTML Table

The <table> tag defines an HTML table.

Each table row is defined with a <tr> tag. Each table header is defined with a <th> tag. Each
table data/cell is defined with a <td> tag.

By default, the text in <th> elements are bold and centered.

By default, the text in <td> elements are regular and left-aligned.

Example

A simple HTML table:

<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: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.

HTML Table - Add a Border

To add a border to a table, use the CSS border property:


Example
table, th, td {
border: 1px solid black;
}

Remember to define borders for both the table and the table cells.

HTML Table - Collapsed Borders

To let the borders collapse into one border, add the CSS border-collapse property:

Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}

HTML Table - Add Cell Padding

Cell padding specifies the space between the cell content and its borders.

If you do not specify a padding, the table cells will be displayed without padding.

To set the padding, use the CSS padding property:

Example
th, td {
padding: 15px;
}

HTML Table - Left-align Headings

By default, table headings are bold and centered.

To left-align the table headings, use the CSS text-align property:

Example
th {
text-align: left;
}

HTML Table - Add Border Spacing

Border spacing specifies the space between the cells.

To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}

Note: If the table has collapsed borders, border-spacing has no effect.

HTML Table - Cell that Span Many Columns

To make a cell span more than one column, use the colspan attribute:

Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>55577854</td>
<td>55577855</td>
</tr>
</table>

HTML Table - Cell that Span Many Rows

To make a cell span more than one row, use the rowspan attribute:

Example
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>

HTML Table - Add a Caption

To add a caption to a table, use the <caption> tag:


Example
<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>
LESSON 5

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Construct a web page with unordered list.
➢ Apply ordered list in web page.
➢ Differentiate block and inline elements.
➢ Utilize class and id attribute in different tags.

Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

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>

Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items will be marked with numbers by default:

Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

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>

HTML Unordered Lists

The HTML <ul> tag defines an unordered (bulleted) list.

Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

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>

Unordered HTML List - Choose List Item Marker

The CSS list-style-type property is used to define the style of the list item marker. It can have
one of the following values:

Value Description

Disc Sets the list item marker to a bullet (default)

Circle Sets the list item marker to a circle

Square Sets the list item marker to a square

None The list items will not be marked


Example - Disc
<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>

Nested HTML Lists

Lists can be nested (list inside list):

Example
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>

HTML Ordered Lists

The HTML <ol> tag defines an ordered list. An ordered list can be numerical or alphabetical.

Ordered HTML List


An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items will be marked with numbers by default:

Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Ordered HTML List - The Type Attribute

The type attribute of the <ol> tag, defines the type of the list item marker:

Type Description

type="1" The list items will be numbered with numbers (default)

type="A" The list items will be numbered with uppercase letters

type="a" The list items will be numbered with lowercase letters

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>

Uppercase Roman Numbers:


<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Lowercase Roman Numbers:


<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Control List Counting

By default, an ordered list will start counting from 1. If you want to start counting from a
specified number, you can use the start attribute:

Example
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Nested HTML Lists

Lists can be nested (list inside list):

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.

HTML Other Lists

HTML also supports description lists.

HTML Description Lists

A description list is a list of terms, with a description of each term.

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>

HTML Block and Inline Elements

Every HTML element has a default display value, depending on what type of element it is.

There are two display values: block and inline.

Block-level Elements

A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
Example

<div>Hello World</div>

Here are the block-level elements in HTML:

Inline Elements

An inline element does not start on a new line and it only takes up as much width as
necessary.

Example:

Here are the inline elements in HTML:


Note: An inline element cannot contain a block-level element!

The <div> Element

The <div> element is often used as a container for other HTML elements.

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>

The <span> Element

The <span> element is an inline container used to mark up a part of a text, or a part of a
document.

The <span> element has no required attributes, but style, class and id are common.

When used together with CSS, the <span> element can be used to style parts of the text:

Example

<p>My mother has <span style="color:blue;font-weight:bold">blue</span> eyes and


my father has <span style="color:darkolivegreen;font-weight:bold">dark
green</span> eyes.</p>

HTML The class Attribute

The HTML class attribute is used to specify a class for an HTML element.

Multiple HTML elements can share the same class.

Using The class Attribute


The class attribute is often used to point to a class name in a style sheet. It can also be used
by a JavaScript to access and manipulate elements with the specific class name.

In the following example we have three <div> elements with a class attribute with the value
of "city". All of the three <div> elements will be styled equally according to the .city style
definition in the head section:

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>

In the following example we have two <span> elements with a class attribute with the value
of "note". Both <span> elements will be styled equally according to the .note style definition
in the head section:

Example

<!DOCTYPE html>
<html>
<head>
<style>
.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>

<h1>My <span class="note">Important</span> Heading</h1>


<p>This is some <span class="note">important</span> text.</p>

</body>
</html>

Tip: The class attribute can be used on any HTML element.

Note: The class name is case sensitive!

The Syntax For Class

To create a class; write a period (.) character, followed by a class name. Then, define the
CSS properties within curly braces {}:

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, the first <h2> element belongs to both the city class and also to
the main class, and will get the CSS styles from both of the classes:

Example

<h2 class="city main">London</h2>


<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

Different Elements Can Share Same Class

Different HTML elements can point to the same class name.

In the following example, both <h2> and <p> points 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>

Use of The class Attribute in JavaScript

The class name can also be used by JavaScript to perform certain tasks for specific
elements.

JavaScript can access elements with a specific class name with


the getElementsByClassName() method:

Example

Click on a button to hide all elements with the class name "city":

<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>

HTML The 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.

Using The id Attribute

The id attribute specifies 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 to point to a specific style declaration in a style sheet. It is also used
by JavaScript to access and manipulate the element with the specific id.

The syntax for id is: write a hash character (#) character, followed by an id name. Then,
define the CSS properties within curly braces {}.

In the following example we have an <h1> element that points to the id name "myHeader".
This <h1> element will be styled according to the #myHeader style definition in the head
section:

Example

<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>

<h1 id="myHeader">My Header</h1>

</body>
</html>
Note: The id name is case sensitive!

Note: The id name must contain at least one character, and must not contain whitespaces
(spaces, tabs, etc.).

Difference Between Class and ID

A class name can be used by multiple HTML elements, while an id name must only be used
by one HTML element within the page:

Example

<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}

/* Style all elements with the class name "city" */


.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>

<!-- An element with a unique id -->


<h1 id="myHeader">My Cities</h1>

<!-- Multiple elements with same class -->


<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>

Tip: You can learn much more about CSS in our CSS Tutorial.
HTML Bookmarks with ID and Links

HTML bookmarks are used to allow readers to jump to specific parts of a webpage.

Bookmarks can be useful if your page is very long.

To use a bookmark, you must first create it, and then add a link to it.

Then, when the link is clicked, the page will scroll to the location with the bookmark.

Example

First, create a bookmark with the id attribute:

<h2 id="C4">Chapter 4</h2>

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>

Or, add a link to the bookmark ("Jump to Chapter 4"), from another page:

<a href="html_demo.html#C4">Jump to Chapter 4</a>

Using The id Attribute in JavaScript

The id attribute can also be used by JavaScript to perform some tasks for that specific
element.

JavaScript can access an element with a specific id with the getElementById() method:

Example

Use the id attribute to manipulate text with JavaScript:

<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>
LESSON 6

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Design a web page using iFrame.
➢ Apply symbols on web page.
➢ Use entity name to display character entities.
➢ Create basic form using HTML.

HTML Iframes

An HTML iframe is used to display a web page within a web page.

HTML Iframe Syntax

The HTML <iframe> tag specifies an inline frame.

An inline frame is used to embed another document within the current HTML document.

Syntax

<iframe src="url" title="description">

Tip: It is a good practice to always include a title attribute for the <iframe>. This is used by
screen readers to read out what the content of the iframe is.

Iframe - Set Height and Width

Use the height and width attributes to specify the size of the iframe.

The height and width are specified in pixels by default:

Example

<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe


Example"></iframe>

Or you can add the style attribute and use the CSS height and width properties:
Example

<iframe src="demo_iframe.htm" style="height:200px;width:300px;" title="Iframe


Example"></iframe>

Iframe - Remove the Border

By default, an iframe has a border around it.

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

<iframe src="demo_iframe.htm" style="border:2px solid red;" title="Iframe


Example"></iframe>

Iframe - Target for a Link

An iframe can be used as the target frame for a link.

The target attribute of the link must refer to the name attribute of the iframe:

Example

<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>

<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

HTML File Paths

A file path describes the location of a file in a web site's folder structure.

File Path Examples


Path Description

<img src="picture.jpg"> The "picture.jpg" file is located in the same folder as the
current page

<img The "picture.jpg" file is located in the images folder in the


src="images/picture.jpg"> current folder

<img The "picture.jpg" file is located in the images folder at the


src="/images/picture.jpg"> root of the current web

<img src="../picture.jpg"> The "picture.jpg" file is located in the folder one level up
from the current folder

HTML File Paths

A file path describes the location of a file in a web site's folder structure.

File paths are used when linking to external files, like:

• Web pages
• Images
• Style sheets
• JavaScripts

Absolute File Paths

An absolute file path is the full URL to a file:

Example

<img src="https://www.w3schools.com/images/picture.jpg" alt="Mountain">

The <img> tag is explained in the chapter: HTML Images.


Relative File Paths

A relative file path points to a file relative to the current page.

In the following example, the file path points to a file in the images folder located at the root
of the current web:

Example

<img src="/images/picture.jpg" alt="Mountain">

In the following example, the file path points to a file in the images folder located in the
current folder:

Example

<img src="images/picture.jpg" alt="Mountain">

In the following example, the file path points to a file in the images folder located in the folder
one level up from the current folder:

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.

HTML - The Head Element

The HTML <head> element is a container for the following


elements: <title>, <style>, <meta>, <link>, <script>, and <base>.

The HTML <head> Element

The <head> element is a container for metadata (data about data) and is placed between
the <html> tag and the <body> tag.

HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, scripts, and other meta
information.

The HTML <title> Element

The <title> element defines the title of the document. The title must be text-only, and it is
shown in the browser's title bar or in the page's tab.

The <title> tag is required in HTML documents!

The contents of a page title is very important for search engine optimization (SEO)! The
page title is used by search engine algorithms to decide the order when listing pages in
search results.

The <title> element:

• defines a title in the browser toolbar


• provides a title for the page when it is added to favorites
• displays a title for the page in search engine-results

So, try to make the title as accurate and meaningful as possible!

A simple HTML document:

Example

<!DOCTYPE html>
<html>
<head>
<title>A Meaningful Page Title</title>
</head>
<body>

The content of the document......

</body>
</html>

The HTML <style> Element

The <style> element is used to define style information for a single HTML page:

Example

<style>
body {background-color: powderblue;}
h1 {color: red;}
p {color: blue;}
</style>

The HTML <link> Element

The <link> element defines the relationship between the current document and an external
resource.

The <link> tag is most often used to link to external style sheets:

Example

<link rel="stylesheet" href="mystyle.css">

The HTML <meta> Element

The <meta> element is typically used to specify the character set, page description,
keywords, author of the document, and viewport settings.

The metadata will not be displayed on the page, but are used by browsers (how to display
content or reload page), by search engines (keywords), and other web services.

Examples

Define the character set used:

<meta charset="UTF-8">

Define keywords for search engines:

<meta name="keywords" content="HTML, CSS, JavaScript">

Define a description of your web page:

<meta name="description" content="Free Web tutorials">

Define the author of a page:

<meta name="author" content="John Doe">

Refresh document every 30 seconds:

<meta http-equiv="refresh" content="30">

Setting the viewport to make your website look good on all devices:

<meta name="viewport" content="width=device-width, initial-scale=1.0">


Example of <meta> tags:

Example

<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="John Doe">

Setting The Viewport

The viewport is the user's visible area of a web page. It varies with the device - it will be
smaller on a mobile phone than on a computer screen.

You should include the following <meta> element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

This gives the browser instructions on how to control the page's dimensions and scaling.

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.

Here is an example of a web page without the viewport meta tag, and the same web
page with the viewport meta tag:

Tip: If you are browsing this page with a phone or a tablet, you can click on the two links
below to see the difference.
Without the viewport meta tag With the viewport meta tag

The HTML <script> Element

The <script> element is used to define client-side JavaScripts.

The following JavaScript writes "Hello JavaScript!" into an HTML element with id="demo":

Example

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>

Tip: To learn all about JavaScript, visit our JavaScript Tutorial.

The HTML <base> Element

The <base> element specifies the base URL and/or target for all relative URLs in a page.

The <base> tag must have either an href or a target attribute present, or both.

There can only be one single <base> element in a document!


Example

Specify a default URL and a default target for all links on a page:

<head>
<base href="https://www.w3schools.com/" target="_blank">
</head>

<body>
<img src="images/stickman.gif" width="24" height="39" alt="Stickman">
<a href="tags/tag_base.asp">HTML base Tag</a>
</body>

HTML Style Guide and Coding Conventions

A consistent, clean, and tidy HTML code makes it easier for others to read and understand
your code.

Here are some guidelines and tips for creating good HTML code.

Always Declare Document Type

Always declare the document type as the first line in your document.

The correct document type for HTML is:

<!DOCTYPE html>

Use Lowercase Element Names

HTML allows mixing uppercase and lowercase letters in element names.

However, we recommend using lowercase element names, because:

• Mixing uppercase and lowercase names looks bad


• Developers normally use lowercase names
• Lowercase looks cleaner
• Lowercase is easier to write

Good:

<body>
<p>This is a paragraph.</p>
</body>
Bad:

<BODY>
<P>This is a paragraph.</P>
</BODY>

Close All HTML Elements

In HTML, you do not have to close all elements (for example the <p> element).

However, we strongly recommend closing all HTML elements, like this:

Good:

<section>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</section>

Bad:

<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>

Use Lowercase Attribute Names

HTML allows mixing uppercase and lowercase letters in attribute names.

However, we recommend using lowercase attribute names, because:

• Mixing uppercase and lowercase names looks bad


• Developers normally use lowercase names
• Lowercase look cleaner
• Lowercase are easier to write

Good:

<a href="https://www.w3schools.com/html/">Visit our HTML tutorial</a>

Bad:

<a HREF="https://www.w3schools.com/html/">Visit our HTML tutorial</a>


Always Quote Attribute Values

HTML allows attribute values without quotes.

However, we recommend quoting attribute values, because:

• Developers normally quote attribute values


• Quoted values are easier to read
• You MUST use quotes if the value contains spaces

Good:

<table class="striped">

Bad:

<table class=striped>

Very bad:

This will not work, because the value contains spaces:

<table class=table striped>

Always Specify alt, width, and height for Images

Always specify the alt attribute for images. This attribute is important if the image for some
reason cannot be displayed.

Also, always define the width and height of images. This reduces flickering, because the
browser can reserve space for the image before loading.

Good:

<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">

Bad:

<img src="html5.gif">

Spaces and Equal Signs

HTML allows spaces around equal signs. But space-less is easier to read and groups
entities better together.
Good:

<link rel="stylesheet" href="styles.css">

Bad:

<link rel = "stylesheet" href = "styles.css">

Avoid Long Code Lines

When using an HTML editor, it is NOT convenient to scroll right and left to read the HTML
code.

Try to avoid too long code lines.

Blank Lines and Indentation

Do not add blank lines, spaces, or indentations without a reason.

For readability, add blank lines to separate large or logical code blocks.

For readability, add two spaces of indentation. Do not use the tab key.

Good:

<body>

<h1>Famous Cities</h1>

<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.
It is the seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family.</p>

</body>

Bad:

<body>

<h1>Famous Cities</h1>

<h2>Tokyo</h2>
<p>
Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.
It is the seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family.
</p>

</body>

Good Table Example:

<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td>A</td>
<td>Description of A</td>
</tr>
<tr>
<td>B</td>
<td>Description of B</td>
</tr>
</table>

Good List Example:

<ul>
<li>London</li>
<li>Paris</li>
<li>Tokyo</li>
</ul>

Never Skip the <title> Element

The <title> element is required in HTML.

The contents of a page title is very important for search engine optimization (SEO)! The
page title is used by search engine algorithms to decide the order when listing pages in
search results.

The <title> element:

• defines a title in the browser toolbar


• provides a title for the page when it is added to favorites
• displays a title for the page in search-engine results
So, try to make the title as accurate and meaningful as possible:

<title>HTML Style Guide and Coding Conventions</title>

Omitting <html> and <body>?

An HTML page will validate without the <html> and <body> tags:

Example

<!DOCTYPE html>
<head>
<title>Page Title</title>
</head>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

However, we strongly recommend to always add the <html> and <body> tags!

Omitting <body> can produce errors in older browsers.

Omitting <html> and <body> can also crash DOM and XML software.

Omitting <head>?

The HTML <head> tag can also be omitted.

Browsers will add all elements before <body>, to a default <head> element.

Example

<!DOCTYPE html>
<html>
<title>Page Title</title>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

However, we recommend using the <head> tag.


Close Empty HTML Elements?

In HTML, it is optional to close empty elements.

Allowed:

<meta charset="utf-8">

Also Allowed:

<meta charset="utf-8" />

If you expect XML/XHTML software to access your page, keep the closing slash (/), because
it is required in XML and XHTML.

Add the lang Attribute

You should always include the lang attribute inside the <html> tag, to declare the language
of the Web page. This is meant to assist search engines and browsers.

Example

<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Meta Data

To ensure proper interpretation and correct search engine indexing, both the language and
the character encoding <meta charset="charset"> should be defined as early as possible in
an HTML document:

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
Setting The Viewport

The viewport is the user's visible area of a web page. It varies with the device - it will be
smaller on a mobile phone than on a computer screen.

You should include the following <meta> element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

This gives the browser instructions on how to control the page's dimensions and scaling.

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.

Here is an example of a web page without the viewport meta tag, and the same web
page with the viewport meta tag:

Tip: If you are browsing this page with a phone or a tablet, you can click on the two links
below to see the difference.

HTML Entities

Reserved characters in HTML must be replaced with character entities.

HTML Entities

Some characters are reserved in HTML.

If you use the less than (<) or greater than (>) signs in your text, the browser might mix them
with tags.

Character entities are used to display reserved characters in HTML.

A character entity looks like this:

&entity_name;

OR

&#entity_number;

To display a less than sign (<) we must write: &lt; or &#60;


Advantage of using an entity name: An entity name is easy to remember.
Disadvantage of using an entity name: Browsers may not support all entity names, but the
support for entity numbers is good.

Non-breaking Space

A commonly used entity in HTML is the non-breaking space: &nbsp;

A non-breaking space is a space that will not break into a new line.

Two words separated by a non-breaking space will stick together (not break into a new line).
This is handy when breaking the words might be disruptive.

Examples:

• § 10
• 10 km/h
• 10 PM

Another common use of the non-breaking space is to prevent browsers from truncating
spaces in HTML pages.

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 &nbsp; character entity.

The non-breaking hyphen (&#8209;) lets you use a hyphen character (-) that won't break.

Some Useful HTML Character Entities


Note: Entity names are case sensitive.

Combining Diacritical Marks

A diacritical mark is a "glyph" added to a letter.

Some diacritical marks, like grave ( ̀) and acute ( ́) are called accents.

Diacritical marks can appear both above and below a letter, inside a letter, and between two
letters.

Diacritical marks can be used in combination with alphanumeric characters to produce a


character that is not present in the character set (encoding) used in the page.

Here are some examples:

HTML Symbols

Symbols that are not present on your keyboard can also be added by using entities.

HTML Symbol Entities

HTML entities were described in the previous chapter.

Many mathematical, technical, and currency symbols, are not present on a normal keyboard.
To add such symbols to an HTML page, you can use an HTML entity name.

If no entity name exists, you can use an entity number, a decimal, or hexadecimal reference.

Example

<p>I will display &euro;</p>


<p>I will display &#8364;</p>
<p>I will display &#x20AC;</p>

Will display as:

I will display €
I will display €
I will display €

Some Greek Letters Supported by HTML


Some Other Entities Supported by HTML

HTML Forms

An HTML form is used to collect user input. The user input can then be sent to a server for
processing.

Example

The <form> Element

The HTML <form> element defines a form that is used to collect user input:

<form>
.
form elements
.
</form>
An HTML form contains form elements.

Form elements are different types of input elements, like: text fields, checkboxes, radio
buttons, submit buttons, and more.

The <input> Element

The <input> element is the most important form element.

The <input> element is displayed in several ways, depending on the type attribute.

Here are some examples:

Text Fields

<input type="text"> defines a single-line input field for text input.

Example

A form with two text input fields:

<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

Notice the use of the <label> element in the example above.

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader will read
out loud the label when the user is focused on the input element.

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.

Radio Buttons

<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

Example

A form with radio buttons:

<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>

The Submit Button

<input type="submit"> defines a button for submitting the form data to a form-handler.
The form-handler is typically a page on the server with a script for processing input data.

The form-handler is specified in the form's action attribute.

Example

A form with a submit button:

<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 Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Usually, the form data is sent to a page on the server when the user clicks on the submit
button.

In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form data:

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

The Target Attribute

The target attribute specifies if the submitted result will open in a new browser tab, a frame,
or in the current window.

The default value is "_self" which means the form will be submitted in the current window.
To make the form result open in a new browser tab, use the value "_blank".

Example

Here, the submitted result will open in a new browser tab:

<form action="/action_page.php" target="_blank">

Other legal values are "_parent", "_top", or a name representing the name of an iframe.

The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data.

Example

Use the GET method when submitting the form:

<form action="/action_page.php" method="get">

or:

Example

Use the POST method when submitting the form:

<form action="/action_page.php" method="post">

When to Use GET?

The default HTTP method when submitting form data is GET.

However, when GET is used, the form data will be visible in the page's address field:

/action_page.php?firstname=John&lastname=Doe

Notes on GET:

• Appends form-data into the URL in name/value pairs


• The length of a URL is limited (2048 characters)
• Never use GET to send sensitive data! (will be visible in the URL)
• Useful for form submissions where a user wants to bookmark the result
• GET is better for non-secure data, like query strings in Google
When to Use POST?

Always use POST if the form data contains sensitive or personal information. The POST
method does not display the form data in the page address field.

Notes on POST:

• POST has no size limitations, and can be used to send large amounts of data.
• Form submissions with POST cannot be bookmarked

The Name Attribute

Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that 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>
LESSON 7

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Design a form using different form elements.
➢ Specify the different input types.
➢ Enumerate the different input attributes of each input type.
➢ Identify the input form attributes used in HTML.

HTML Form Elements

This chapter describes all the different HTML form elements.

The <input> Element

One of the most used form element is the <input> element.

The <input> element can be displayed in several ways, depending on the type attribute.

Example

<input type="text" id="firstname" name="firstname">

If the type attribute is omitted, the input field gets the default type: "text".

The <select> Element

The <select> element defines a drop-down list:

Example

<select id="cars" name="cars">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <option> elements defines an option that can be selected.

By default, the first item in the drop-down list is selected.


To define a pre-selected option, add the selected attribute to the option:

Example

<option value="fiat" selected>Fiat</option>

Visible Values:

Use the size attribute to specify the number of visible values:

Example

<select name="cars" size="3">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

Allow Multiple Selections:

Use the multiple attribute to allow the user to select more than one value:

Example

<select name="cars" size="4" multiple>


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):

Example

<textarea name="message" rows="10" cols="30">


The cat was playing in the garden.
</textarea>

The rows attribute specifies the visible number of lines in a text area.

The cols attribute specifies the visible width of a text area.


This is how the HTML code above will be displayed in a browser:

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>

The <button> Element

The <button> element defines a clickable button:

Example

<button type="button" onclick="alert('Hello World!')">Click Me!</button>

This is how the HTML code above will be displayed in a browser:

Note: Always specify the type attribute for the button element. Different browsers may use
different default types for the button element.

The <fieldset> and <legend> Elements

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> 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>

This is how the HTML code above will be displayed in a browser:

The <datalist> Element

The <datalist> element specifies a list of pre-defined options for an <input> element.

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="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
The <output> Element

The <output> element represents the result of a calculation (like one performed by a script).

Example

Perform a calculation and show the result in an <output> element:

<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>

HTML Input Types

This chapter describes the different types for the HTML <input> element.

HTML Input Types

Here are the different input types you can use in HTML:

• <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">

Input Type Text

<input type="text"> defines a single-line text input field:

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>

This is how the HTML code above will be displayed in a browser:

Input Type Password

<input type="password"> defines a password field:

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>

This is how the HTML code above will be displayed in a browser:


The characters in a password field are masked (shown as asterisks or circles).

Input Type Submit

<input type="submit"> defines a button for submitting form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

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>

This is how the HTML code above will be displayed in a browser:

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">
</form>
Input Type Reset

<input type="reset"> defines a reset button that will reset all form values to their default
values:

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">
</form>

This is how the HTML code above will be displayed in a browser:

If you change the input values and then click the "Reset" button, the form-data will be reset
to the default values.

Input Type Radio

<input type="radio"> defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example

<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>

This is how the HTML code above will be displayed in a browser:


Input Type Checkbox

<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>

This is how the HTML code above will be displayed in a browser:

Input Type Button

<input type="button"> defines a button:

Example

<input type="button" onclick="alert('Hello World!')" value="Click Me!">

This is how the HTML code above will be displayed in a browser:

Input Type Color

The <input type="color"> is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example

<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>

Input Type Date

The <input type="date"> is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

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.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
</form>

Input Type Email

The <input type="email"> is used for input fields that should contain an e-mail address.
Depending on browser support, the e-mail address can be automatically validated when
submitted.

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>

Input Type File

The <input type="file"> defines a file-select field and a "Browse" button for file uploads.

Example

<form>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
</form>

Input Type Month

The <input type="month"> allows the user to select a month and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth">
</form>

Input Type Number

The <input type="number"> defines a numeric input field.

You can also set restrictions on what numbers are accepted.

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:

Example

<form>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="0" max="100" step="10" v
alue="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>

Input Type Search

The <input type="search"> is used for search fields (a search field behaves like a regular
text field).

Example

<form>
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
</form>

Input Type Tel

The <input type="tel"> is used for input fields that should contain a telephone number.

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>

Input Type Time

The <input type="time"> allows the user to select a time (no time zone).

Depending on browser support, a time picker can show up in the input field.

Example

<form>
<label for="appt">Select a time:</label>
<input type="time" id="appt" name="appt">
</form>

Input Type Url

The <input type="url"> is used for input fields that should contain a URL address.
Depending on browser support, the url field can be automatically validated when submitted.

Some smartphones recognize the url type, and adds ".com" to the keyboard to match url
input.

Example

<form>
<label for="homepage">Add your homepage:</label>
<input type="url" id="homepage" name="homepage">
</form>

Input Type Week

The <input type="week"> allows the user to select a week and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
</form>

HTML Input Attributes

This chapter describes the different attributes for the HTML <input> element.

The value Attribute

The input value attribute specifies an initial value for an input field:

Example

Input fields with initial (default) values:

<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>
The readonly Attribute

The input readonly attribute specifies that an input field is read-only.

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!

Example

A read-only input field:

<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 disabled Attribute

The input disabled attribute specifies that an input field should be disabled.

A disabled input field is unusable and un-clickable.

The value of a disabled input field will not be sent when submitting the form!

Example

A disabled input field:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" disabled><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The size Attribute

The input size attribute specifies the visible width, in characters, of an input field.

The default value for size is 20.

Note: The size attribute works with the following input types: text, search, tel, url, email, and
password.
Example

Set a width for an input field:

<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>

The maxlength Attribute

The input maxlength attribute specifies the maximum number of characters allowed in an
input field.

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

Set a maximum length for an input field:

<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" maxlength="4" size="4">
</form>

The min and max Attributes

The input min and max attributes specify the minimum and maximum values for an input
field.

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.

Example

Set a max date, a min date, and 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>

<label for="datemin">Enter a date after 2000-01-01:</label>


<input type="date" id="datemin" name="datemin" min="2000-01-02"><br><br>

<label for="quantity">Quantity (between 1 and 5):</label>


<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>

The multiple Attribute

The input multiple attribute specifies that the user is allowed to enter more than one value in
an input field.

The multiple attribute works with the following input types: email, and file.

Example

A file upload field that accepts multiple values:

<form>
<label for="files">Select files:</label>
<input type="file" id="files" name="files" multiple>
</form>

The pattern Attribute

The input pattern attribute specifies a regular expression that the input field's value is
checked against, when the form is submitted.

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.

Tip: Learn more about regular expressions in our JavaScript tutorial.

Example

An input field that can contain only three letters (no numbers or special characters):

<form>
<label for="country_code">Country code:</label>
<input type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}" title="Three letter country code">
</form>

The placeholder Attribute


The input placeholder attribute specifies short a hint that describes the expected value of an
input field (a sample value or a short description of the expected format).

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.

Example

An input field with a placeholder text:

<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>

The required Attribute

The input required attribute specifies that an input field must be filled out before submitting
the form.

The required attribute works with the following input types: text, search, url, tel, email,
password, date pickers, number, checkbox, radio, and file.

Example

A required input field:

<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</form>

The step Attribute

The input step attribute specifies the legal number intervals for an input field.

Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.

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)!

The autofocus Attribute

The input autofocus attribute specifies that an input field should automatically get focus when
the page loads.

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>

The height and width Attributes

The input height and width attributes specify the height and width of an <input
type="image"> element.

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>

The list Attribute

The input list attribute refers to a <datalist> element that contains pre-defined options for an
<input> element.

Example

An <input> element with pre-defined values in a <datalist>:

<form>
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>

The autocomplete Attribute

The input autocomplete attribute specifies whether a form or an input field should have
autocomplete on or off.

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.

The autocomplete attribute works with <form> and the following <input> types: text, search,
url, tel, email, password, datepickers, range, and color.

Example

An HTML form with autocomplete on, and off for one input field:

<form action="/action_page.php" autocomplete="on">


<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>
<label for="email">Email:</label>
<input type="email" id="email" name="email" autocomplete="off"><br><br>
<input type="submit" value="Submit">
</form>
HTML Input form* Attributes

This chapter describes the different form* attributes for the HTML <input> element.

The form Attribute

The input form attribute specifies the form the <input> element belongs to.

The value of this attribute must be equal to the id attribute of the <form> element it belongs
to.

Example

An input field located outside of the HTML form (but still a part of the form):

<form action="/action_page.php" id="form1">


<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="submit" value="Submit">
</form>

<label for="lname">Last name:</label>


<input type="text" id="lname" name="lname" form="form1">

The formaction Attribute

The input formaction attribute specifies the URL of the file that will process the input when
the form is submitted.

Note: This attribute overrides the action attribute of the <form> element.

The formaction attribute works with the following input types: submit and image.

Example

An HTML form with two submit buttons, with different actions:

<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

The input formenctype attribute specifies how the form-data should be encoded when
submitted (only for forms with method="post").

Note: This attribute overrides the enctype attribute of the <form> element.

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":

<form action="/action_page_binary.asp" method="post">


<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formenctype="multipart/form-data"
value="Submit as Multipart/form-data">
</form>

The formmethod Attribute

The input formmethod attribute defines the HTTP method for sending form-data to the action
URL.

Note: This attribute overrides the method attribute of the <form> element.

The formmethod attribute works with the following input types: submit and image.

The form-data can be sent as URL variables (method="get") or as an HTTP post transaction
(method="post").

Notes on the "get" method:

• This method appends the form-data to the URL in name/value pairs


• This method is useful for form submissions where a user want to bookmark the result
• There is a limit to how much data you can place in a URL (varies between browsers),
therefore, you cannot be sure that all of the form-data will be correctly transferred
• Never use the "get" method to pass sensitive information! (password or other
sensitive information will be visible in the browser's address bar)

Notes on the "post" method:

• This method sends the form-data as an HTTP post transaction


• Form submissions with the "post" method cannot be bookmarked
• The "post" method is more robust and secure than "get", and "post" does not have
size limitations

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":

<form action="/action_page.php" method="get">


<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 using GET">
<input type="submit" formmethod="post" value="Submit using POST">
</form>

The formtarget Attribute

The input formtarget a attribute specifies a name or a keyword that indicates where to
display the response that is received after submitting the form.

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

The input formnovalidate attribute specifies that an <input> element should not be validated
when submitted.

Note: This attribute overrides the novalidate attribute of the <form> element.

The formnovalidate attribute works with the following input types: submit.
Example

A form with two submit buttons (with and without validation):

<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>

The novalidate Attribute

The novalidate attribute is a <form> attribute.

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:

<form action="/action_page.php" novalidate>


<label for="email">Enter your email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
LESSON 8

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Draw graphics using Canvass and SVG.
➢ Identify and explain the different media that can be added to website.
➢ Integrate video on web page.

HTML Canvas Graphics

The HTML <canvas> element is used to draw graphics on a web page.

The graphic to the left is created with <canvas>. It shows four elements: a red rectangle, a
gradient rectangle, a multicolor rectangle, and a multicolor text.

What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

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.

Browser Support

The numbers in the table specify the first browser version that fully supports
the <canvas> element.
Canvas Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and
no content.

The markup looks like this:

<canvas id="myCanvas" width="200" height="100"></canvas>

Note: Always specify an id attribute (to be referred to in a script), and


a width and height attribute to define the size of the canvas. To add a border, use
the style attribute.

Here is an example of a basic, empty canvas:

Example

<canvas id="myCanvas" width="200" height="100" style="border:1px solid


#000000;"> </canvas>

Draw a Line

Example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
Draw a Circle

Example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

Draw a Text

Example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);

Stroke Text
Example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);

Draw Linear Gradient

Example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");

// Fill with gradient


ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

Draw Circular Gradient

Example
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");

// Fill with gradient


ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

Draw Image

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);

HTML SVG Graphics

SVG defines vector-based graphics in XML format.

What is SVG?

• SVG stands for Scalable Vector Graphics


• SVG is used to define graphics for the Web
• SVG is a W3C recommendation

The HTML <svg> Element

The HTML <svg> element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

Browser Support

The numbers in the table specify the first browser version that fully supports
the <svg> element.
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 Rounded Rectangle

Example

<svg width="400" height="180">


<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</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>

Differences Between SVG and Canvas

SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG DOM. You
can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are
changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the
browser. If its position should be changed, the entire scene needs to be redrawn, including
any objects that might have been covered by the graphic.
Comparison of Canvas and SVG

The table below shows some important differences between Canvas and SVG:

HTML Multimedia

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.

Web pages often contain multimedia elements of different types and formats.

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.

Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv,
and .avi.
Only MP4, WebM, and Ogg video are supported by the HTML standard.

Common Audio Formats

MP3 is the best format for compressed recorded music. The term MP3 has become
synonymous with digital music.

If your website is about recorded music, MP3 is the choice.


Only MP3, WAV, and Ogg audio are supported by the HTML standard.

HTML Video

The HTML <video> element is used to show a video on a web page.

The HTML <video> Element

To show a video in HTML, use the <video> element:

Example

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

How it Works

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are not set,
the page might flicker while the video loads.

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.

HTML <video> Autoplay

To start a video automatically use the autoplay attribute:

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>

The autoplay attribute does not work in mobile devices like iPad and iPhone.
LESSON 9

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Integrate audio on web page.
➢ Enumerate the apply plugins in web page.
➢ Demonstrate how to add embed YouTube videos on web page.

HTML Audio

The HTML <audio> element is used to play an audio file on a web page.

The HTML <audio> Element

To play an audio file in HTML, use the <audio> element:

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>

HTML Audio - How It Works

The controls attribute adds audio controls, like play, pause, and volume.

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.

HTML Plug-ins

Plug-ins are computer programs that extend the standard functionality of the browser.
Plug-ins

Plug-ins were designed to be used for many different purposes:

• To run Java applets


• To run Microsoft ActiveX controls
• To display Flash movies
• To display maps
• To scan for viruses
• To verify a bank id

Warning !

Most browsers no longer support Java Applets and Plug-ins.

ActiveX controls are no longer supported in any browsers.

The support for Shockwave Flash has also been turned off in modern browsers.

The <object> Element

The <object> element is supported by all browsers.

The <object> element defines an embedded object within an HTML document.

It was designed to embed plug-ins (like Java applets, PDF readers, and Flash Players) in
web pages, but can also be used to include HTML in HTML:

Example

<object width="100%" height="500px" data="snippet.html"></object>

Or images if you like:

Example

<object data="audi.jpeg"></object>

The <embed> Element

The <embed> element is supported in all major browsers.

The <embed> element also defines an embedded object within an HTML document.
Web browsers have supported the <embed> element for a long time. However, it has not
been a part of the HTML specification before HTML5.

Example

<embed src="audi.jpeg">

Note that the <embed> element does not have a closing tag. It can not contain alternative
text.

The <embed> element can also be used to include HTML in HTML:

Example

<embed width="100%" height="500px" src="snippet.html">

HTML YouTube Videos

The easiest way to play videos in HTML, is to use YouTube.

Struggling with Video Formats?

Earlier in this tutorial, you have seen that you might have to convert your videos to different
formats to make them play in all browsers.

Converting videos to different formats can be difficult and time-consuming.

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.

Playing a YouTube Video in HTML

To play your video on a web page, do the following:

• Upload the video to YouTube


• Take a note of the video id
• Define an <iframe> element in your web page
• Let the src attribute point to the video URL
• Use the width and height attributes to specify the dimension of the player
• Add any other parameters to the URL (see below)
Example

<iframe width="420" height="315"


src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>

YouTube Autoplay

You can have your video start playing automatically when a user visits that page by adding a
simple parameter to your YouTube URL.

Note: Take careful consideration when deciding to autoplay your videos. Automatically
starting a video can annoy your visitor and end up causing more harm than good.

Value 0 (default): The video will not play automatically when the player loads.

Value 1: The video will play automatically when the player loads.

YouTube - Autoplay

<iframe width="420" height="315"


src="https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1">
</iframe>

YouTube Playlist

A comma separated list of videos to play (in addition to the original URL).

YouTube Loop

Value 0 (default): The video will play only once.

Value 1: The video will loop (forever).

YouTube - Loop

<iframe width="420" height="315"


src="https://www.youtube.com/embed/tgbNymZ7vqY?playlist=tgbNymZ7vqY&loop=1"
></iframe>

YouTube Controls

Value 0: Player controls does not display.

Value 1 (default): Player controls display.


YouTube - Controls

<iframe width="420" height="315"


src="https://www.youtube.com/embed/tgbNymZ7vqY?controls=0">
</iframe>
MODULE 2 – INTRODUCTION TO COMPUTING

LESSON 10

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Define and explain CSS.
➢ Create simple CSS file.
➢ Enumerate and differentiate different CSS selectors.
➢ Use CSS comment to document CSS code.

CSS Introduction

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

Why Use CSS?


CSS is used to define styles for your web pages, including the design, layout and variations in
display for different devices and screen sizes.

CSS Example
CSS Solved a Big Problem

HTML was NEVER intended to contain tags for formatting a web page!

HTML was created to describe the content of a web page, like:

<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.

CSS removed the style formatting from the HTML page!

CSS Saves a Lot of Work!

The style definitions are normally saved in external .css files.

With an external stylesheet file, you can change the look of an entire website by changing just
one file!

CSS Syntax

A CSS rule-set consists of a selector and a declaration block:

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.
Example

In this example all <p> elements will be center-aligned, with a red text color:

Example Explained

• p is a selector in CSS (it points to the HTML element you want to style: <p>).
• color is a property, and red is the property value
• text-align is a property, and center is the property value

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

• Simple selectors (select elements based on name, id, class)


• Combinator selectors (select elements based on a specific relationship between
them)
• Pseudo-class selectors (select elements based on a certain state)
• Pseudo-elements selectors (select and style a part of an element)
• Attribute selectors (select elements based on an attribute or attribute value)

The CSS element Selector

The element selector selects HTML elements based on the element name.
Here, all <p> elements on the page will be center-aligned, with a red text color:

The CSS id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique
element!

To select an element with a specific id, write a hash (#) character, followed by the id of the
element.

Example

The CSS rule below will be applied to the HTML element with id="para1":

Note: An id name cannot start with a number!


The CSS class Selector

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class
name.

Example

In this example all HTML elements with class="center" will be red and center-aligned:

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 center-aligned:


HTML elements can also refer to more than one class.

Example

In this example the <p> element will be styled according to class="center" and to class="large":

Note: A class name cannot start with a number!

The CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

Example

The CSS rule below will affect

every HTML element on the page:


The CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

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;
}

It will be better to group the selectors, to minimize the code.

To group selectors, separate each selector with a comma.

Example

In this example we have grouped the selectors from the code above:
All CSS Simple Selectors

How To Add CSS

When a browser reads a style sheet, it will format the HTML document according to the
information in the style sheet.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

• External CSS

• Internal CSS

• Inline CSS

External CSS

With an external style sheet, you can change the look of an entire website by changing just
one file!

Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML
page:
An external style sheet can be written in any text editor, and must be saved with a .css
extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks like:

"mystyle.css"

body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}

Note: Do not add a space between the property value and the unit (such as margin-left: 20
px;). The correct way is: margin-left: 20px;

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML
page:
Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

Tip: An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly.

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets,
the value from the last read style sheet will be used.

Assume that an external style sheet has the following style for the <h1> element:

h1 {
color: navy;
}

Then, assume that an internal style sheet also has the following style for the <h1> element:

h1 {
color: orange;
}
Example

If the internal style is defined after the link to the external style sheet, the <h1> elements will
be "orange":

Example

However, if the internal style is defined before the link to the external style sheet, the <h1>
elements will be "navy":

Cascading Order

What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules,
where number one has the highest priority:

1. Inline style (inside an HTML element)


2. External and internal style sheets (in the head section)
3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and
browser defaults.

SS Comments

Comments are used to explain the code, and may help when you edit the source code at a
later date.

Comments are ignored by browsers.

A CSS comment is placed inside the <style> element, and starts with /* and ends with */:

Example

You can add comments wherever you want in the code:


Example

Comments can also span multiple lines:

Example

HTML and CSS Comments

From the HTML tutorial, you learned that you can add comments to your HTML source by
using the <!--...--> syntax.
In the following example, we use a combination of HTML and CSS comments:

Example
LESSON 11

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Use CSS colors to design web page elements.
➢ Apply cell padding in web design.
➢ Create and utilize different borders and its attributes.
➢ Use CSS padding in designing web page.

CSS Colors

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA
values.

CSS Color Names

Example
CSS Background Color

You can set the background color for HTML elements:

Example

CSS 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.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.
Example

CSS Border Color

You can set the color of borders:

Example

CSS Color Values

In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA
values, and HSLA values:
Same as color name "Tomato":

Same as color name "Tomato", but 50% transparent:

Example

CSS RGB Colors

RGB Value

In CSS, a color can be specified as an RGB value, using this formula:

rgb(red, green, blue)


Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255)
and the others are set to 0.

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).

Example

Shades of gray are often defined using equal values for all the 3 light sources:

Example
RGBA Value

RGBA color values are an extension of RGB color values with an alpha channel - which
specifies the opacity for a color.

An RGBA color value is specified with:

rgba(red, green, blue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at
all):

Example

CSS HEX Colors

HEX Value

In CSS, a color can be specified using a hexadecimal value in the form:

#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as
decimal 0-255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the
others are set to the lowest value (00).

Example:

Shades of gray are often defined using equal values for all the 3 light sources:
CSS HSL Colors

HSL Value

In CSS, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(hue, saturation, lightness)

Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white

Example:

Saturation

Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray

50% is 50% gray, but you can still see the color.
0% is completely gray, you can no longer see the color.

Example:

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) 100% means full
lightness (white).

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the lightness
from 0% to 100% to get darker/lighter shades:

Example:
HSLA Value

HSLA color values are an extension of HSL color values with an alpha channel - which specifies
the opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

CSS Backgrounds

The CSS background properties are used to define the background effects for elements.

In these chapters, you will learn about the following CSS background properties:

• background-color

• background-image

• background-repeat
• background-attachment

• background-position

SS background-image

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Example

The background image for a page can be set like this:


This example shows a bad combination of text and background image. The text is hardly
readable:

Note: When using a background image, use an image that does not disturb the text.

CSS Background Repeat

CSS background-repeat

By default, the background-image property repeats an image both horizontally and vertically.

Some images should be repeated only horizontally or vertically, or they will look strange, like
this:
Example

If the image above is repeated only horizontally (background-repeat: repeat-x;), the


background will look better:

Example
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
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

Position the background image in the top-right corner:

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
SS background-attachment

The background-attachment property specifies whether the background image should scroll
or be fixed (will not scroll with the rest of the page):

Example

Specify that the background image should be fixed:

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 - 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;
}

You can use the shorthand property background:

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.

CSS Borders

CSS Border Properties

The CSS border properties allow you to specify the style, width, and color of an element's
border.

CSS Border Style

The border-style property specifies what kind of border to display.

The following values are allowed:

• dotted - Defines a dotted border


• dashed - Defines a dashed border
• solid - Defines a solid border
• double - Defines a double border
• groove - Defines a 3D grooved border. The effect depends on the border-color value
• ridge - Defines a 3D ridged border. The effect depends on the border-color value
• inset - Defines a 3D inset border. The effect depends on the border-color value
• outset - Defines a 3D outset border. The effect depends on the border-color value
• none - Defines no border
• hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).

Example

Demonstration of the different border styles:

p.dotted {border-style: dotted;}


p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
CSS Border Width

The border-width property specifies the width of the four borders.

The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three
pre-defined values: thin, medium, or thick:

Example

Demonstration of the different border widths:

p.one {
border-style: solid;
border-width: 5px;
}

p.two {
border-style: solid;
border-width: medium;
}

p.three {
border-style: dotted;
border-width: 2px;
}

p.four {
border-style: dotted;
border-width: thick;
}
Result

Specific Side Widths

The border-width property can have from one to four values (for the top border, right border,
bottom border, and the left border):

Example

CSS Border Color

The border-color property is used to set the color of the four borders.

The color can be set by:

• name - specify a color name, like "red"


• HEX - specify a HEX value, like "#ff0000"
• RGB - specify a RGB value, like "rgb(255,0,0)"
• HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
• transparent

Note: If border-color is not set, it inherits the color of the element.

Example

Demonstration of the different border colors:


Specific Side Colors

The border-color property can have from one to four values (for the top border, right border,
bottom border, and the left border).

Example

p.one {
border-style: solid;
border-color: red green blue yellow; /* red top, green right, blue bottom and yellow left */
}

CSS Border - Individual Sides

From the examples on the previous pages, you have seen that it is possible to specify a
different border for each side.

In CSS, there are also properties for specifying each of the borders (top, right, bottom, and
left):

Example

p{
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}

The example above gives the same result as this:

Example

p{
border-style: dotted solid;
}

So, here is how it works:

If the border-style property has four values:

• border-style: dotted solid double dashed;


o top border is dotted
o right border is solid
o bottom border is double
o left border is dashed
If the border-style property has three values:

• border-style: dotted solid double;


o top border is dotted
o right and left borders are solid
o bottom border is double

If the border-style property has two values:

• border-style: dotted solid;


o top and bottom borders are dotted
o right and left borders are solid

If the border-style property has one value:

• border-style: dotted;
o all four borders are dotted

Example
CSS Border - Shorthand Property

Like you saw in the previous page, there are many properties to consider when dealing with
borders.

To shorten the code, it is also possible to specify all the individual border properties in one
property.

The border property is a shorthand property for the following individual border properties:

• border-width
• border-style (required)
• border-color

Example

p{
border: 5px solid red;
}

Left Border

p{
border-left: 6px solid red;
background-color: lightgrey;
}

Bottom Border

p{
border-bottom: 6px solid red;
background-color: lightgrey;
}

CSS Rounded Borders

The border-radius property is used to add rounded borders to an element:


CSS Margins

The CSS margin properties are used to create space around elements, outside of any
defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin
for each side of an element (top, right, bottom, and left).

Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:
• margin-top
• margin-right
• margin-bottom
• margin-left

All the margin properties can have the following values:

• auto - the browser calculates the margin


• length - specifies a margin in px, pt, cm, etc.
• % - specifies a margin in % of the width of the containing element
• inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example

Set different margins for all four sides of a <p> element:

p{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}

Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin properties:

• margin-top
• margin-right
• margin-bottom
• margin-left

So, here is how it works:

If the margin property has four values:

• margin: 25px 50px 75px 100px;


o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

Example

Use the margin shorthand property with four values:


p{
margin: 25px 50px 75px 100px;
}

If the margin property has three values:

• margin: 25px 50px 75px;


o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

Example

Use the margin shorthand property with three values:

p{
margin: 25px 50px 75px;
}

If the margin property has two values:

• margin: 25px 50px;


o top and bottom margins are 25px
o right and left margins are 50px

Example

Use the margin shorthand property with two values:

p{
margin: 25px 50px;
}

If the margin property has one value:

• margin: 25px;
o all four margins are 25px

Example

Use the margin shorthand property with one value:

p{
margin: 25px;
}

The auto Value


You can set the margin property to auto to horizontally center the element within its
container.

The element will then take up the specified width, and the remaining space will be split
equally between the left and right margins.

Example

Use margin: auto:

div {
width: 300px;
margin: auto;
border: 1px solid red;
}

The inherit Value

This example lets the left margin of the <p class="ex1"> element be inherited from the parent
element (<div>):

Example

Use of the inherit value:

div {
border: 1px solid red;
margin-left: 100px;
}

p.ex1 {
margin-left: inherit;
}

Margin Collapse

Top and bottom margins of elements are sometimes collapsed into a single margin that is
equal to the largest of the two margins.

This does not happen on left and right margins! Only top and bottom margins!

Look at the following example:

Example

Demonstration of margin collapse:


h1 {
margin: 0 0 50px 0;
}

h2 {
margin: 20px 0 0 0;
}

In the example above, the <h1> element has a bottom margin of 50px and the <h2> element
has a top margin set to 20px.

Common sense would seem to suggest that the vertical margin between the <h1> and the
<h2> would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin
ends up being 50px.

CSS Padding

The CSS padding properties are used to generate space around an element's content,
inside of any defined borders.

With CSS, you have full control over the padding. There are properties for setting the
padding for each side of an element (top, right, bottom, and left).

Padding - Individual Sides

CSS has properties for specifying the padding for each side of an element:

• padding-top
• padding-right
• padding-bottom
• padding-left

All the padding properties can have the following values:

• length - specifies a padding in px, pt, cm, etc.


• % - specifies a padding in % of the width of the containing element
• inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.


Example

Set different padding for all four sides of a <div> element:

Padding - Shorthand Property

To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding properties:

• padding-top
• padding-right
• padding-bottom
• padding-left

So, here is how it works:

If the padding property has four values:

• padding: 25px 50px 75px 100px;


o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px

Example
Use the padding shorthand property with four values:

div {
padding: 25px 50px 75px 100px;
}

If the padding property has three values:

• padding: 25px 50px 75px;


o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px

Example

Use the padding shorthand property with three values:

div {
padding: 25px 50px 75px;
}

If the padding property has two values:

• padding: 25px 50px;


o top and bottom paddings are 25px
o right and left paddings are 50px

1. Example

Use the padding shorthand property with two values:

div {
padding: 25px 50px;
}

If the padding property has one value:

• padding: 25px;
o all four paddings are 25px

Example

Use the padding shorthand property with one value:

div {
padding: 25px;
}

Padding and Element Width


The CSS width property specifies the width of the element's content area. The content area
is the portion inside the padding, border, and margin of an element (the box model).

So, if an element has a specified width, the padding added to that element will be added to
the total width of the element. This is often an undesirable result.

Example

Here, the <div> element is given a width of 300px. However, the actual width of the <div>
element will be 350px (300px + 25px of left padding + 25px of right padding):

div {
width: 300px;
padding: 25px;
}

To keep the width at 300px, no matter the amount of padding, you can use the box-
sizing property. This causes the element to maintain its width; if you increase the padding,
the available content space will decrease.

Example

Use the box-sizing property to keep the width at 300px, no matter the amount of padding:

div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
LESSON 12

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Use CSS height & width code to adjust elements in the web page.
➢ Apply box model concept to strategize web design.
➢ Create and experiment on CSS outlines.
➢ Use different font styles and formatting.

CSS Height and Width

CSS Setting height and width

The height and width properties are used to set the height and width of an element.

The height and width properties do not include padding, borders, or margins. It sets the
height/width of the area inside the padding, border, and margin of the element.

CSS height and width Values

The height and width properties may have the following values:

• auto - This is default. The browser calculates the height and width
• length - Defines the height/width in px, cm etc.
• % - Defines the height/width in percent of the containing block
• initial - Sets the height/width to its default value
• inherit - The height/width will be inherited from its parent value

CSS height and width Examples


Example

Set the height and width of another <div> element:

div {
height: 100px;
width: 500px;
background-color: powderblue;
}

Note: Remember that the height and width properties do not include padding, borders, or
margins! They set the height/width of the area inside the padding, border, and margin of the
element!

Setting max-width

The max-width property is used to set the maximum width of an element.

The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the
containing block, or set to none (this is default. Means that there is no maximum width).

The problem with the <div> above occurs when the browser window is smaller than the width
of the element (500px). The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small
windows.
Tip: Drag the browser window to smaller than 500px wide, to see the difference between the
two divs!

Note: The value of the max-width property overrides width.

Example

This <div> element has a height of 100 pixels and a max-width of 500 pixels:

div {
max-width: 500px;
height: 100px;
background-color: powderblue;
}

The CSS Box Model

All HTML elements can be considered as boxes. In CSS, the term "box model" is used when
talking about design and layout.

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:

Explanation of the different parts:

• 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:


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

This <div> element will have a total width of 350px:

div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

Here is the calculation:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left
margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border
+ top margin + bottom margin

CSS Outline

An outline is a line that is drawn around elements, OUTSIDE the borders, to make
the element "stand out".
Sample:

Result:
Note: None of the other outline properties (which you will learn more about in the next
chapters) will have ANY effect unless the outline-style property is set!

CSS Outline Width

The outline-width property specifies the width of the outline, and can have one of
the following values:

• thin (typically 1px)


• medium (typically 3px)
• thick (typically 5px)
• A specific size (in px, pt, cm, em, etc)

The following example shows some outlines with different widths:

Example

p.ex1 {
border: 1px solid black;
outline-style: solid;
outline-color: red;
outline-width: thin;
}
p.ex2 {
border: 1px solid black;
outline-style: solid;
outline-color: red;
outline-width: medium;
}

p.ex3 {
border: 1px solid black;
outline-style: solid;
outline-color: red;
outline-width: thick;
}

p.ex4 {
border: 1px solid black;
outline-style: solid;
outline-color: red;
outline-width: 4px;
}

CSS Outline Color

The outline-color property is used to set the color of the outline.

The color can be set by:

• name - specify a color name, like "red"


• HEX - specify a hex value, like "#ff0000"
• RGB - specify a RGB value, like "rgb(255,0,0)"
• HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
• invert - performs a color inversion (which ensures that the outline is visible, regardless
of color background)

The following example shows some different outlines with different colors. Also notice that
these elements also have a thin black border inside the outline:

Example

p.ex1 {
border: 2px solid black;
outline-style: solid;
outline-color: red;
}

p.ex2 {
border: 2px solid black;
outline-style: dotted;
outline-color: blue;
}

p.ex3 {
border: 2px solid black;
outline-style: outset;
outline-color: grey;
}

HEX Values

The outline color can also be specified using a hexadecimal value (HEX):

Example

p.ex1 {
outline-style: solid;
outline-color: #ff0000; /* red */
}

RGB Values

Or by using RGB values:

Example

p.ex1 {
outline-style: solid;
outline-color: rgb(255, 0, 0); /* red */
}

HSL Values

You can also use HSL values:

Example
p.ex1 {
outline-style: solid;
outline-color: hsl(0, 100%, 50%); /* red */
}

Invert Color

The following example uses outline-color: invert, which performs a color inversion. This
ensures that the outline is visible, regardless of color background:

A solid invert outline.

Example

p.ex1 {
border: 1px solid yellow;
outline-style: solid;
outline-color: invert;
}

CSS Outline - Shorthand property

The outline property is a shorthand property for setting the following individual outline
properties:

• outline-width
• outline-style (required)
• outline-color

The outline property is specified as one, two, or three values from the list above. The order
of the values does not matter.

The following example shows some outlines specified with the shorthand outline property:

Example:
SS Outline Offset

The outline-offset property adds space between an outline and the edge/border of an
element. The space between an element and its outline is transparent.

The following example specifies an outline 15px outside the border edge:

Example:
The following example shows that the space between an element and its outline is transparent:

Example

p{
margin: 30px;
background: yellow;
border: 1px solid black;
outline: 1px solid red;
outline-offset: 15px;
}

CSS Text

Text Color

The color property is used to set the color of the text. The color is specified by:

• a color name - like "red"


• a HEX value - like "#ff0000"
• an RGB value - like "rgb(255,0,0)"

Look at CSS Color Values for a complete list of possible color values.
The default text color for a page is defined in the body selector.

Example

Text Color and Background Color

In this example, we define both the background-color property and the color property:

Example

body {
background-color: lightgrey;
color: blue;
}

h1 {
background-color: black;
color: white;
}
CSS Text Alignment

Text Alignment

The text-align property is used to set the horizontal alignment of a text.

A text can be left or right aligned, centered, or justified.

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;
}

When the text-align property is set to "justify", each line is stretched so that every line has
equal width, and the left and right margins are straight (like in magazines and newspapers):

Example

div {
text-align: 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;
}
Vertical Alignment

The vertical-align property sets the vertical alignment of an element.

This example demonstrates how to set the vertical alignment of an image in a text:

Example

img.top {
vertical-align: top;
}

img.middle {
vertical-align: middle;
}

img.bottom {
vertical-align: bottom;
}

CSS Text Decoration

Text Decoration

The text-decoration property is used to set or remove decorations from text.

The value text-decoration: none; is often used to remove underlines from links:

Example

a{
text-decoration: none;
}

The other text-decoration values are used to decorate text:

Example

h1 {
text-decoration: overline;
}

h2 {
text-decoration: line-through;
}

h3 {
text-decoration: underline;
}
Note: It is not recommended to underline text that is not a link, as this often confuses the
reader.

CSS Text Transformation

Text Transformation

The text-transform property is used to specify uppercase and lowercase letters in a text.

It can be used to turn everything into uppercase or lowercase letters, or capitalize the first
letter of each word:

Example

p.uppercase {
text-transform: uppercase;
}

p.lowercase {
text-transform: lowercase;
}

p.capitalize {
text-transform: capitalize;
}

CSS Text Spacing

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.

The following example demonstrates how to increase or decrease the space between
characters:

Example
h1 {
letter-spacing: 3px;
}

h2 {
letter-spacing: -3px;
}

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

h1 {
word-spacing: 10px;
}

h2 {
word-spacing: -5px;
}

White Space

The white-space property specifies how white-space inside an element is handled.

This example demonstrates how to disable text wrapping inside an element:

Example

p{
white-space: nowrap;
}
CSS Text Shadow

Text Shadow

The text-shadow property adds shadow to text.

In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow
(2px):

Example

h1 {
text-shadow: 2px 2px;
}

Next, add a color (red) to the shadow:

Example

h1 {
text-shadow: 2px 2px red;
}

Then, add a blur effect (5px) to the shadow:

Example

h1 {
text-shadow: 2px 2px 5px red;
}

CSS Fonts
The CSS font properties define the font family, boldness, size, and the style of a text.

Difference Between Serif and Sans-serif Fonts

CSS Font Families

In CSS, there are two types of font family names:

• generic family - a group of font families with a similar look (like "Serif" or
"Monospace")
• font family - a specific font family (like "Times New Roman" or "Arial")

Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.

Font Family

The font family of a text is set with the font-family property.

The font-family property should hold several font names as a "fallback" system. If the
browser does not support the first font, it tries the next font, and so on.

Start with the font you want, and end with a generic family, to let the browser pick a similar
font in the generic family, if no other fonts are available.

Note: If the name of a font family is more than one word, it must be in quotation marks, like:
"Times New Roman".
More than one font family is specified in a comma-separated list:

Example

Specify the font for three paragraphs:

.serif {
font-family: "Times New Roman", Times, serif;
}

.sansserif {
font-family: Arial, Helvetica, sans-serif;
}

.monospace {
font-family: "Lucida Console", Courier, monospace;
}

Example

Specify the "Impact" font for a paragraph:

p.impact {
font-family: Impact, Charcoal, sans-serif;
}

CSS Font Style

Font Style

The font-style property is mostly used to specify italic text.

This property has three values:

• normal - The text is shown normally


• italic - The text is shown in italics
• oblique - The text is "leaning" (oblique is very similar to italic, but less supported)

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.

In a small-caps font, all lowercase letters are converted to uppercase letters. However, the
converted uppercase letters appears in a smaller font size than the original uppercase letters
in the text.

Example

p.normal {
font-variant: normal;
}

p.small {
font-variant: small-caps;
}

CSS Font Size

Font Size

The font-size property sets the size of the text.

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.

The font-size value can be an absolute, or relative size.

Absolute size:
• Sets the text to a specified size
• Does not allow a user to change the text size in all browsers (bad for accessibility
reasons)
• Absolute size is useful when the physical size of the output is known

Relative size:

• Sets the size relative to surrounding elements


• Allows a user to change the text size in browsers

Note: If you do not specify a font size, the default size for normal text, like paragraphs, is
16px (16px=1em).

Set Font Size with Pixels

Setting the text size with pixels gives you full control over the text size:

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.

Set Font Size With Em

To allow users to resize the text (in the browser menu), many developers use em instead of
pixels.

The em size unit is recommended by the W3C.

1em is equal to the current font size. The default text size in browsers is 16px. So, the
default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

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.

Unfortunately, there is still a problem with older versions of Internet Explorer. The text
becomes larger than it should when made larger, and smaller than it should when made
smaller.

Use a Combination of Percent and Em

The solution that works in all browsers, is to set a default font-size in percent for the <body>
element:

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!

Responsive Font Size

The text size can be set with a vw unit, which means the "viewport width".
That way the text size will follow the size of the browser window:

Example

<h1 style="font-size:10vw">Hello World</h1>

CSS Google Fonts

Google Fonts

If you do not want to use any of the standard fonts in HTML, you can use the Google Fonts
API to add hundreds of other fonts to your page.

Just add a stylesheet link and refer to a font family of your choice:

Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia">
<style>
body {
font-family: "Sofia";
font-size: 22px;
}
</style>
</head>
<body>

<h1>Sofia Font</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>

</body>
</html>
CSS Font Property

Font Property

To shorten the code, it is also possible to specify all the individual font properties in one
property.

The font property is a shorthand property for:

• font-style
• font-variant
• font-weight
• font-size/line-height
• font-family

Example

Set some font properties with the shorthand declaration:

p.a {
font: 20px Arial, sans-serif;
}

p.b {
font: italic small-caps bold 12px/30px Georgia, serif;
}

Note: The font-size and font-family values are required. If one of the other values is missing,
their default value are used.
LESSON 13

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Insert icons on web page.
➢ Create and design links and tables using CSS
➢ Enhance Unordered and Ordered list using CSS.

CSS Icons

How To Add Icons

The simplest way to add an icon to your HTML page, is with an icon library, such as Font
Awesome.

Add the name of the specified icon class to any inline HTML element (like <i> or <span>).

All the icons in the icon libraries below, are scalable vectors that can be customized with
CSS (size, color, shadow, etc.)

Font Awesome Icons

To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add in
the <head> section of your HTML page:

<script src="https://kit.fontawesome.com/yourcode.js"></script>

Read more about how to get started with Font Awesome in our Font Awesome 5 tutorial.

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<body>
<i class="fas fa-cloud"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>

</body>
</html>

Bootstrap Icons

To use the Bootstrap glyphicons, add the following line inside the <head> section of your
HTML page:

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Note: No downloading or installation is required!

Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/boot
strap.min.css">
</head>
<body>

<i class="glyphicon glyphicon-cloud"></i>


<i class="glyphicon glyphicon-remove"></i>
<i class="glyphicon glyphicon-user"></i>
<i class="glyphicon glyphicon-envelope"></i>
<i class="glyphicon glyphicon-thumbs-up"></i>

</body>
</html>

Google Icons

To use the Google icons, add the following line inside the <head> section of your HTML
page:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Note: No downloading or installation is required!


Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>

<i class="material-icons">cloud</i>
<i class="material-icons">favorite</i>
<i class="material-icons">attachment</i>
<i class="material-icons">computer</i>
<i class="material-icons">traffic</i>

</body>
</html>

CSS Links

With CSS, links can be styled in different ways

Styling Links

Links can be styled with any CSS property (e.g. color, font-family, background, etc.).

Example

a{
color: hotpink;
}

In addition, links can be styled differently depending on what state they are in.

The four links states are:

• a:link - a normal, unvisited link


• a:visited - a link the user has visited
• a:hover - a link when the user mouses over it
• a:active - a link the moment it is clicked

Example

/* unvisited link */
a:link {
color: red;
}

/* visited link */
a:visited {
color: green;
}

/* mouse over link */


a:hover {
color: hotpink;
}

/* selected link */
a:active {
color: blue;
}

When setting the style for several link states, there are some order rules:

• a:hover MUST come after a:link and a:visited


• a:active MUST come after a:hover

Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example

a:link {
text-decoration: none;
}

a:visited {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

a:active {
text-decoration: underline;
}
Background Color

The background-color property can be used to specify a background color for links:

Example

a:link {
background-color: yellow;
}

a:visited {
background-color: cyan;
}

a:hover {
background-color: lightgreen;
}

a:active {
background-color: hotpink;
}

Link Buttons

This example demonstrates a more advanced example where we combine several CSS
properties to display links as boxes/buttons:

Example

a:link, a:visited {
background-color: #f44336;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}

a:hover, a:active {
background-color: red;
}
CSS Lists

HTML Lists and CSS List Properties

In HTML, there are two main types of lists:

• unordered lists (<ul>) - the list items are marked with bullets
• ordered lists (<ol>) - the list items are marked with numbers or letters

The CSS list properties allow you to:

• Set different list item markers for ordered lists


• Set different list item markers for unordered lists
• Set an image as the list item marker
• Add background colors to lists and list items

Different List Item Markers

The list-style-type property specifies the type of list item marker.

The following example shows some of the available list item markers:

Example

ul.a {
list-style-type: circle;
}

ul.b {
list-style-type: square;
}

ol.c {
list-style-type: upper-roman;
}

ol.d {
list-style-type: lower-alpha;
}

Note: Some of the values are for unordered lists, and some for ordered lists.

An Image as The List Item Marker

The list-style-image property specifies an image as the list item marker:

Example

ul {
list-style-image: url('sqpurple.gif');
}

Position The List Item Markers

The list-style-position property specifies the position of the list-item markers (bullet points).

"list-style-position: outside;" means that the bullet points will be outside the list item. The start
of each line of a list item will be aligned vertically. This is default:

"list-style-position: inside;" means that the bullet points will be inside the list item. As it is part
of the list item, it will be part of the text and push the text at the start:

Example

ul.a {
list-style-position: outside;
}
ul.b {
list-style-position: inside;
}

Remove Default Settings

The list-style-type:none property can also be used to remove the markers/bullets. Note that
the list also has default margin and padding. To remove this, add margin:0 and padding:0 to
<ul> or <ol>:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
}

List - Shorthand property

The list-style property is a shorthand property. It is used to set all the list properties in one
declaration:

Example

ul {
list-style: square inside url("sqpurple.gif");
}

When using the shorthand property, the order of the property values are:

• list-style-type (if a list-style-image is specified, the value of this property will be


displayed if the image for some reason cannot be displayed)
• list-style-position (specifies whether the list-item markers should appear inside or
outside the content flow)
• list-style-image (specifies an image as the list item marker)

If one of the property values above are missing, the default value for the missing property will
be inserted, if any.

Styling List With Colors

We can also style lists with colors, to make them look a little more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the
<li> tag will affect the individual list items:
Example

ol {
background: #ff9999;
padding: 20px;
}

ul {
background: #3399ff;
padding: 20px;
}

ol li {
background: #ffe5e5;
padding: 5px;
margin-left: 35px;
}

ul li {
background: #cce5ff;
margin: 5px;
}

CSS Tables

The look of an HTML table can be greatly improved with CSS:

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Berglunds snabbköp Christina Berglund Sweden

Centro comercial Moctezuma Francisco Chang Mexico


Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Königlich Essen Philip Cramer Germany

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Table Borders

To specify table borders in CSS, use the border property.

The example below specifies a black border for <table>, <th>, and <td> elements:

Example

table, th, td {
border: 1px solid black;
}

Notice that the table in the example above has double borders. This is because both the
table and the <th> and <td> elements have separate borders.

Collapse Table Borders

The border-collapse property sets whether the table borders should be collapsed into a
single border:
Example

table {
border-collapse: collapse;
}

table, th, td {
border: 1px solid black;
}

If you only want a border around the table, only specify the border property for <table>:

Example

table {
border: 1px solid black;
}

CSS Layout - The Display Property

The display property is the most important CSS property for controlling layout.

The display Property

The display property specifies if/how an element is displayed.

Every HTML element has a default display value depending on what type of element it is.
The default display value for most elements is block or inline.

Click to show panel

Block-level Elements

A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).

The <div> element is a block-level element.


Examples of block-level elements:

• <div>
• <h1> - <h6>
• <p>
• <form>
• <header>
• <footer>
• <section>

Inline Elements

An inline element does not start on a new line and only takes up as much width as
necessary.

This is an inline <span> element inside a paragraph.

Examples of inline elements:

• <span>
• <a>
• <img>

Display: none;

display: none; is commonly used with JavaScript to hide and show elements without deleting
and recreating them. Take a look at our last example on this page if you want to know how
this can be achieved.

The <script> element uses display: none; as default.

Override The Default Display Value

As mentioned, every element has a default display value. However, you can override this.

Changing an inline element to a block element, or vice versa, can be useful for making the
page look a specific way, and still follow the web standards.

A common example is making inline <li> elements for horizontal menus:

Example
li {
display: inline;
}

Note: Setting the display property of an element only changes how the element is displayed,
NOT what kind of element it is. So, an inline element with display: block; is not allowed to have
other block elements inside it.

The following example displays <span> elements as block elements:

Example

span {
display: block;
}

The following example displays <a> elements as block elements:

Example

a{
display: block;
}

Hide an Element - display:none or visibility:hidden?

Hiding an element can be done by setting the display property to none. The element will be
hidden, and the page will be displayed as if the element is not there:

Example

h1.hidden {
display: none;
}

visibility:hidden; also hides an element.

However, the element will still take up the same space as before. The element will be
hidden, but still affect the layout:

Example

h1.hidden {
visibility: hidden;
}
LESSON 14

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Differentiate CSS width and CSS max-width
➢ Set elements position using CSS.
➢ Apply overflow on design if necessary.
➢ Utilize CSS float and CSS inline in designing web page.

CSS Layout - width and max-width

Using width, max-width and margin: auto;

As mentioned in the previous chapter; a block-level element always takes up the full width
available (stretches out to the left and right as far as it can).

Setting the width of a block-level element will prevent it from stretching out to the edges of its
container. Then, you can set the margins to auto, to horizontally center the element within its
container. The element will take up the specified width, and the remaining space will be split
equally between the two margins:

Note: The problem with the <div> above occurs when the browser window is smaller than the
width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small
windows. This is important when making a site usable on small devices:

Tip: Resize the browser window to less than 500px wide, to see the difference between the
two divs!

Here is an example of the two divs above:


Example

div.ex1 {
width: 500px;
margin: auto;
border: 3px solid #73AD21;
}

div.ex2 {
max-width: 500px;
margin: auto;
border: 3px solid #73AD21;
}

CSS Layout - The position Property

The position property specifies the type of positioning method used for an element (static,
relative, fixed, absolute or sticky).

The position Property

The position property specifies the type of positioning method used for an element.

There are five different position values:

• 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.

An element with position: static; is not positioned in any special way; it is always positioned
according to the normal flow of the page:
Here is the CSS that is used:

Example

div.static {
position: static;
border: 3px solid #73AD21;
}

position: relative;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause
it to be adjusted away from its normal position. Other content will not be adjusted to fit into
any gap left by the element.

Example

div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}

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:

Example

div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}

This <div> element has position: fixed;

position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the


document body, and moves along with page scrolling.

Note: A "positioned" element is one whose position is anything except static.

Here is a simple example:

Here is the CSS that is used:

Example

div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
position: sticky;

An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is
positioned relative until a given offset position is met in the viewport - then it "sticks" in place
(like position:fixed).

Note: Internet Explorer, Edge 15 and earlier versions do 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

div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}

Overlapping Elements

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be
placed in front of, or behind, the others).

An element can have a positive or negative stack order:


Example

img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}

An element with greater stack order is always in front of an element with a lower stack order.

Note: If two positioned elements overlap without a z-index specified, the element positioned
last in the HTML code will be shown on top.

Positioning Text In an Image

How to position text over an image:

Example
CSS Layout - Overflow

The CSS overflow property controls what happens to content that is too big to fit into an
area.

SS Overflow

The overflow property specifies whether to clip the content or to add scrollbars when the
content of an element is too big to fit in the specified area.

The overflow property has the following values:

• visible - Default. The overflow is not clipped. The content renders outside the
element's box
• hidden - The overflow is clipped, and the rest of the content will be invisible
• scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
• auto - Similar to scroll, but it adds scrollbars only when necessary

Note: The overflow property only works for block elements with a specified height.
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being
used (even though "overflow:scroll" is set).

overflow: visible

By default, the overflow is visible, meaning that it is not clipped and it renders outside the
element's box:

Example:

overflow: hidden

With the hidden value, the overflow is clipped, and the rest of the content is hidden:
Example

div {
overflow: hidden;
}

overflow: scroll

Setting the value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the
box. Note that this will add a scrollbar both horizontally and vertically (even if you do not
need it):

Example

div {
overflow: scroll;
}

overflow: auto

The auto value is similar to scroll, but it adds scrollbars only when necessary:

Example

div {
overflow: auto;
}
overflow-x and overflow-y

The overflow-x and overflow-y properties specifies whether to change the overflow of content
just horizontally or vertically (or both):

overflow-x specifies what to do with the left/right edges of the content.


overflow-y specifies what to do with the top/bottom edges of the content.

Example

div {
overflow-x: hidden; /* Hide horizontal scrollbar */
overflow-y: scroll; /* Add vertical scrollbar */
}

CSS Layout - float and clear

The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on
which side.

The float Property

The float property is used for positioning and formatting content e.g. let an image float left to
the text in a container.

The float property can have one of the following values:

• left - The element floats to the left of its container


• right - The element floats to the right of its container
• none - The element does not float (will be displayed just where it occurs in the text).
This is default
• inherit - The element inherits the float value of its parent

In its simplest use, the float property can be used to wrap text around images.
Example - float: right;

The following example specifies that an image should float to the right in a text:

Example - float: left;

The following example specifies that an image should float to the left in a text:
Example

img {
float: left;
}

Example - No float

In the following example the image will be displayed just where it occurs in the text (float:
none;):

Example

img {
float: none;
}

CSS Layout - clear and clearfix

The clear Property

The clear property specifies what elements can float beside the cleared element and on
which side.

The clear property can have one of the following values:

• none - Allows floating elements on both sides. This is default


• left - No floating elements allowed on the left side
• right- No floating elements allowed on the right side
• both - No floating elements allowed on either the left or the right side
• inherit - The element inherits the clear value of its parent

The most common way to use the clear property is after you have used a float property on
an element.
When clearing floats, you should match the clear to the float: If an element is floated to the
left, then you should clear to the left. Your floated element will continue to float, but the
cleared element will appear below it on the web page.

The following example clears the float to the left. Means that no floating elements are
allowed on the left side (of the div):

Example

div {
clear: left;
}

The clearfix Hack

If an element is taller than the element containing it, and it is floated, it will "overflow" outside
of its container:
The overflow: auto clearfix works well as long as you are able to keep control of your margins
and padding (else you might see scrollbars). The new, modern clearfix hack however, is
safer to use, and the following code is used for most webpages:

Example

.clearfix::after {
content: "";
clear: both;
display: table;
}

CSS Layout - display: inline-block

The display: inline-block Value

Compared to display: inline, the major difference is that display: inline-block allows to set a
width and height on the element.
Also, with display: inline-block, the top and bottom margins/paddings are respected, but
with display: inline they are not.

Compared to display: block, the major difference is that display: inline-block does not add a
line-break after the element, so the element can sit next to other elements.

The following example shows the different behavior of display: inline, display: inline-
block and display: block:

Example

span.a {
display: inline; /* the default for span */
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}

span.b {
display: inline-block;
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}

span.c {
display: block;
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}

Using inline-block to Create Navigation Links

One common use for display: inline-block is to display list items horizontally instead of
vertically. The following example creates horizontal navigation links:

Example

.nav {
background-color: yellow;
list-style-type: none;
text-align: center;
padding: 0;
margin: 0;
}

.nav li {
display: inline-block;
font-size: 20px;
padding: 20px;
}
LESSON 15

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Demonstrate how to align web page elements horizontally and vertically.
➢ Show how CSS combinators work.
➢ Differentiate the application of pseudo-class and pseudo-element.
➢ Utilize CSS float and CSS inline in designing web page.

CSS Layout - Horizontal & Vertical Align

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the edges of its
container.

The element will then take up the specified width, and the remaining space will be split
equally between the two margins:

Example

.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set to 100%).
Center Align Text

To just center the text inside an element, use text-align: center;

Example

.center {
text-align: center;
border: 3px solid green;
}

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Example

img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:


Note: Absolute positioned elements are removed from the normal flow, and can overlap
elements.

Left and Right Align - Using float

Another method for aligning elements is to use the float property:

Example

.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}

Note: If an element is taller than the element containing it, and it is floated, it will overflow
outside of its container. You can use the "clearfix" hack to fix this (see example below).

The clearfix Hack

Without Clearfix

With Clearfix
Then we can add overflow: auto; to the containing element to fix this problem:

Example

.clearfix {
overflow: auto;
}

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top
and bottom padding:

I am vertically centered.

Example

.center {
padding: 70px 0;
border: 3px solid green;
}

To center both vertically and horizontally, use padding and text-align: center:

Example

.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}

Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal to
the height property:

Example
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}

/* If the text has multiple lines, add the following: */


.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}

Center Vertically - Using position & transform

If padding and line-height are not options, another solution is to use positioning and

Example

.center {
height: 200px;
position: relative;
border: 3px solid green;
}

.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Tip: You will learn more about the transform property in our 2D Transforms Chapter.

Center Vertically - Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and
earlier versions:

I am vertically and horizontally centered.

Example

.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}

CSS Combinators

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors,
we can include a combinator.

There are four different combinators in CSS:

• descendant selector (space)


• child selector (>)
• adjacent sibling selector (+)
• general sibling selector (~)

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside <div> elements:

Example

div p {
background-color: yellow;
}

Child Selector

The child selector selects all elements that are the children of a specified element.

The following example selects all <p> elements that are children of a <div> element:

Example

div > p {
background-color: yellow;
}

Adjacent Sibling Selector


The adjacent sibling selector selects all elements that are the adjacent siblings of a specified
element.

Sibling elements must have the same parent element, and "adjacent" means "immediately
following".

The following example selects all <p> elements that are placed immediately after <div>
elements:

Example

div + p {
background-color: yellow;
}

General Sibling Selector

The general sibling selector selects all elements that are siblings of a specified element.

The following example selects all <p> elements that are siblings of <div> elements:

Example

div ~ p {
background-color: yellow;
}

CSS Pseudo-classes

What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

• Style an element when a user mouses over it


• Style visited and unvisited links differently
• Style an element when it gets focus

Syntax

The syntax of pseudo-classes:


selector:pseudo-class {
property: value;
}

Anchor Pseudo-classes

Links can be displayed in different ways:

Example

/* unvisited link */
a:link {
color: #FF0000;
}

/* visited link */
a:visited {
color: #00FF00;
}

/* mouse over link */


a:hover {
color: #FF00FF;
}

/* 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.

Pseudo-classes and CSS Classes

Pseudo-classes can be combined with CSS classes:

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;
}

Simple Tooltip Hover

Hover over a <div> element to show a <p> element (like a tooltip):

Hover over me to show the <p> element.

Example

p{
display: none;
background-color: yellow;
padding: 20px;
}

div:hover p {
display: block;
}

CSS - The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first child of another
element.

Match the first <p> element

In the following example, the selector matches any <p> element that is the first child of any
element:

Example
p:first-child {
color: blue;
}

Match the first <i> element in all <p> elements

In the following example, the selector matches the first <i> element in all <p> elements:

Example

p i:first-child {
color: blue;
}

Match all <i> elements in all first child <p> elements

In the following example, the selector matches all <i> elements in <p> elements that are the
first child of another element:

Example

p:first-child i {
color: blue;
}

CSS - The :lang Pseudo-class

The :lang pseudo-class allows you to define special rules for different languages.

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>

<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>


</body>
</html>

CSS Pseudo-elements

What are Pseudo-Elements?

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

• Style the first letter, or line, of an element


• Insert content before, or after, the content of an element

Syntax

The syntax of pseudo-elements:

selector::pseudo-element {
property: value;
}

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.

The following example formats the first line of the text in all <p> elements:

Example

p::first-line {
color: #ff0000;
font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-line pseudo-element:

• font properties
• color properties
• background properties
• word-spacing
• letter-spacing
• text-decoration
• vertical-align
• text-transform
• line-height
• clear

Notice the double colon notation - ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was
an attempt from W3C to distinguish between pseudo-classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2
and CSS1.

For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1
pseudo-elements.

The ::first-letter Pseudo-element

The ::first-letter pseudo-element is used to add a special style to the first letter of a text.

The following example formats the first letter of the text in all <p> elements:

Example

p::first-letter {
color: #ff0000;
font-size: xx-large;
}

Note: The ::first-letter pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-letter pseudo- element:

• 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

Pseudo-elements and CSS Classes

Pseudo-elements can be combined with CSS classes:


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.

In the following example, the first letter of a paragraph will be red, in an xx-large font size.
The rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the
default font size and color:

Example

p::first-letter {
color: #ff0000;
font-size: xx-large;
}

p::first-line {
color: #0000ff;
font-variant: small-caps;
}

CSS - The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before the content of an
element.

The following example inserts an image before the content of each <h1> element:

Example

h1::before {
content: url(smiley.gif);
}

CSS - The ::after Pseudo-element

The ::after pseudo-element can be used to insert some content after the content of an
element.
The following example inserts an image after the content of each <h1> element:

Example

h1::after {
content: url(smiley.gif);
}

CSS - The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is selected by a user.

The following CSS properties can be applied to ::selection: color, background, cursor,
and outline.

The following example makes the selected text red on a yellow background:

Example

::selection {
color: red;
background: yellow;
}

CSS Opacity / Transparency

The opacity property specifies the opacity/transparency of an element.

Transparent Image

The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent:

Example
img {
opacity: 0.5;
}

Transparent Hover Effect

The opacity property is often used together with the :hover selector to change the opacity on
mouse-over:

Example

img {
opacity: 0.5;
}

img:hover {
opacity: 1.0;
}

Example explained

The first CSS block is similar to the code in Example 1. In addition, we have added what
should happen when a user hovers over one of the images. In this case we want the image
to NOT be transparent when the user hovers over it. The CSS for this is opacity:1;.

When the mouse pointer moves away from the image, the image will be transparent again.

An example of reversed hover effect:

Example

img:hover {
opacity: 0.5;
}

Transparent Box

When using the opacity property to add transparency to the background of an element, all of
its child elements inherit the same transparency. This can make the text inside a fully
transparent element hard to read:
Example

div {
opacity: 0.3;
}

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above,
use RGBA color values. The following example sets the opacity for the background color
and not the text:

Example

div {
background: rgba(76, 175, 80, 0.3) /* Green background with 30% opacity */
}

Text in Transparent Box

Example

<html>
<head>
<style>
div.background {
background: url(klematis.jpg) repeat;
border: 2px solid black;
}

div.transbox {
margin: 30px;
background-color: #ffffff;
border: 1px solid black;
opacity: 0.6;
}

div.transbox p {
margin: 5%;
font-weight: bold;
color: #000000;
}
</style>
</head>
<body>

<div class="background">
<div class="transbox">
<p>This is some text that is placed in the transparent box.</p>
</div>
</div>

</body>
</html>

Example explained

First, we create a <div> element (class="background") with a background image, and a


border.

Then we create another <div> (class="transbox") inside the first <div>.

The <div class="transbox"> have a background color, and a border - the div is transparent.

Inside the transparent <div>, we add some text inside a <p> element.
LESSON 16

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Develop and design web page with navigation and dropdown using CSS.
➢ Create image gallery using CSS.
➢ Apply image sprite concept and attribute selector in a web page.

CSS Navigation Bar

Navigation Bars

Having easy-to-use navigation is important for any web site.

With CSS you can transform boring HTML menus into good-looking navigation bars.

Navigation Bar = List of Links

A navigation bar needs standard HTML as a base.

In our examples we will build the navigation bar from a standard HTML list.

A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect
sense:

Example

<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>

Now let's remove the bullets and the margins and padding from the list:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
}

Example explained:

• list-style-type: none; - Removes the bullets. A navigation bar does not need list
markers
• Set margin: 0; and padding: 0; to remove browser default settings

CSS Vertical Navigation Bar

Vertical Navigation Bar

To build a vertical navigation bar, you can style the <a> elements inside the list, in addition to
the code from the previous page:

Example

li a {
display: block;
width: 60px;
}

Example explained:

• display: block; - Displaying the links as block elements makes the whole link area
clickable (not just the text), and it allows us to specify the width (and padding, margin,
height, etc. if you want)
• width: 60px; - Block elements take up the full width available by default. We want to
specify a 60 pixels width

You can also set the width of <ul>, and remove the width of <a>, as they will take up the full
width available when displayed as block elements. This will produce the same result as our
previous example:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 60px;
}

li a {
display: block;
}

Vertical Navigation Bar Examples

Create a basic vertical navigation bar with a gray background color and change the
background color of the links when the user moves the mouse over them:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}

li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}

/* Change the link color on hover */


li a:hover {
background-color: #555;
color: white;
}

Active/Current Navigation Link

Add an "active" class to the current link to let the user know which page he/she is on:
Center Links & Add Borders

Add text-align:center to <li> or <a> to center the links.

Add the border property to <ul> add a border around the navbar. If you also want borders
inside the navbar, add a border-bottom to all <li> elements, except for the last one:
Example

ul {
border: 1px solid #555;
}

li {
text-align: center;
border-bottom: 1px solid #555;
}

li:last-child {
border-bottom: none;
}

Full-height Fixed Vertical Navbar

Create a full-height, "sticky" side navigation:

Example
Note: This example might not work properly on mobile devices.

CSS Horizontal Navigation Bar

Horizontal Navigation Bar

There are two ways to create a horizontal navigation bar. Using inline or floating list items.

Inline List Items

One way to build a horizontal navigation bar is to specify the <li> elements as inline, in
addition to the "standard" code from the previous page:

Example

li {
display: inline;
}

Example explained:

• display: inline; - By default, <li> elements are block elements. Here, we remove the
line breaks before and after each list item, to display them on one line
Floating List Items

Another way of creating a horizontal navigation bar is to float the <li> elements, and specify
a layout for the navigation links:

Example

li {
float: left;
}

a{
display: block;
padding: 8px;
background-color: #dddddd;
}

Example explained:

• float: left; - use float to get block elements to slide next to each other
• display: block; - Displaying the links as block elements makes the whole link area
clickable (not just the text), and it allows us to specify padding (and height, width,
margins, etc. if you want)
• padding: 8px; - Since block elements take up the full width available, they cannot float
next to each other. Therefore, specify some padding to make them look good
• background-color: #dddddd; - Add a gray background-color to each a element

Tip: Add the background-color to <ul> instead of each <a> element if you want a full-width
background color:

Example

ul {
background-color: #dddddd;
}

Horizontal Navigation Bar Examples

Create a basic horizontal navigation bar with a dark background color and change the
background color of the links when the user moves the mouse over them:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

li {
float: left;
}

li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

/* Change the link color to #111 (black) on hover */


li a:hover {
background-color: #111;
}

Active/Current Navigation Link

Add an "active" class to the current link to let the user know which page he/she is on:

Example

.active {
background-color: #4CAF50;
}

Right-Align Links

Right-align links by floating the list items to the right (float:right;):

Example

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li style="float:right"><a class="active" href="#about">About</a></li>
</ul>

Border Dividers

Add the border-right property to <li> to create link dividers:

Example

/* Add a gray right border to all list items, except the last item (last-child) */
li {
border-right: 1px solid #bbb;
}

li:last-child {
border-right: none;
}

Fixed Navigation Bar

Make the navigation bar stay at the top or the bottom of the page, even when the user scrolls
the page:

Example:

ul {
position: fixed;
top: 0;
width: 100%;
}
Example:

ul {
position: fixed;
bottom: 0;
width: 100%;
}

Note: Fixed position might not work properly on mobile devices.

Gray Horizontal Navbar

An example of a gray horizontal navigation bar with a thin gray border:

Example

ul {
border: 1px solid #e7e7e7;
background-color: #f3f3f3;
}

li a {
color: #666;
}

Sticky Navbar
Add position: sticky; to <ul> to create a sticky navbar.

A sticky element toggles between relative and fixed, depending on the scroll position. It is
positioned relative until a given offset position is met in the viewport - then it "sticks" in place
(like position:fixed).

Example

ul {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
}

Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning.
Safari requires a -webkit- prefix (see example above). You must also specify at least one
of top, right, bottom or left for sticky positioning to work.

CSS Dropdowns

Basic Dropdown

Create a dropdown box that appears when the user moves the mouse over an element.

Example

<style>
.dropdown {
position: relative;
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}

.dropdown:hover .dropdown-content {
display: block;
}
</style>

<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>

Example Explained

HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button>
element.

Use a container element (like <div>) to create the dropdown content and add whatever you
want inside of it.

Wrap a <div> element around the elements to position the dropdown content correctly with
CSS.

CSS) The .dropdown class uses position:relative, which is needed when we want the
dropdown content to be placed right below the dropdown button (using position:absolute).

The .dropdown-content class holds the actual dropdown content. It is hidden by default, and
will be displayed on hover (see below). Note the min-width is set to 160px. Feel free to
change this. Tip: If you want the width of the dropdown content to be as wide as the
dropdown button, set the width to 100% (and overflow:auto to enable scroll on small
screens).

Instead of using a border, we have used the CSS box-shadow property to make the
dropdown menu look like a "card".

The :hover selector is used to show the dropdown menu when the user moves the mouse
over the dropdown button.

Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:

This example is similar to the previous one, except that we add links inside the dropdown
box and style them to fit a styled dropdown button:

Example

<style>
/* Style The Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}

/* The container <div> - needed to position the dropdown content */


.dropdown {
position: relative;
display: inline-block;
}

/* Dropdown Content (Hidden by Default) */


.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

/* Links inside the dropdown */


.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

/* Change color of dropdown links on hover */


.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu on hover */


.dropdown:hover .dropdown-content {
display: block;
}

/* Change the background color of the dropdown button when the dropdown content
is shown */
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>

<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

Right-aligned Dropdown Content

If you want the dropdown menu to go from right to left, instead of left to right, add right: 0;

Example

.dropdown-content {
right: 0;
}

More Examples

Dropdown Image

How to add an image and other content inside the dropdown box.
Dropdown Navbar

How to add a dropdown menu inside a navigation bar.


CSS Image Gallery

Image Gallery

The following image gallery is created with CSS:

Example

<html>
<head>
<style>
div.gallery {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}

div.gallery:hover {
border: 1px solid #777;
}

div.gallery img {
width: 100%;
height: auto;
}

div.desc {
padding: 15px;
text-align: center;
}
</style>
</head>
<body>

<div class="gallery">
<a target="_blank" href="img_5terre.jpg">
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
<a target="_blank" href="img_forest.jpg">
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
<a target="_blank" href="img_lights.jpg">
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
<a target="_blank" href="img_mountains.jpg">
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>

CSS Image Sprites

Image Sprites

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server
requests.

Using image sprites will reduce the number of server requests and save bandwidth.

Image Sprites - Simple Example

Instead of using three separate images, we use this single image ("img_navsprites.gif"):

With CSS, we can show just the part of the image we need.

In the following example the CSS specifies which part of the "img_navsprites.gif" image to
show:

Example

#home {
width: 46px;
height: 44px;
background: url(img_navsprites.gif) 0 0;
}

Example explained:
• <img id="home" src="img_trans.gif"> - Only defines a small transparent image
because the src attribute cannot be empty. The displayed image will be the
background image we specify in CSS
• width: 46px; height: 44px; - Defines the portion of the image we want to use
• background: url(img_navsprites.gif) 0 0; - Defines the background image and its
position (left 0px, top 0px)

This is the easiest way to use image sprites, now we want to expand it by using links and
hover effects.

Image Sprites - Create a Navigation List

We want to use the sprite image ("img_navsprites.gif") to create a navigation list.

We will use an HTML list, because it can be a link and also supports a background image:

Example

#navlist {
position: relative;
}

#navlist li {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
top: 0;
}

#navlist li, #navlist a {


height: 44px;
display: block;
}

#home {
left: 0px;
width: 46px;
background: url('img_navsprites.gif') 0 0;
}

#prev {
left: 63px;
width: 43px;
background: url('img_navsprites.gif') -47px 0;
}
#next {
left: 129px;
width: 43px;
background: url('img_navsprites.gif') -91px 0;
}

Example explained:

• #navlist {position:relative;} - position is set to relative to allow absolute positioning


inside it
• #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} - margin and
padding are set to 0, list-style is removed, and all list items are absolute positioned
• #navlist li, #navlist a {height:44px;display:block;} - the height of all the images are
44px

Now start to position and style for each specific part:

• #home {left:0px;width:46px;} - Positioned all the way to the left, and the width of the
image is 46px
• #home {background:url(img_navsprites.gif) 0 0;} - Defines the background image and
its position (left 0px, top 0px)
• #prev {left:63px;width:43px;} - Positioned 63px to the right (#home width 46px + some
extra space between items), and the width is 43px.
• #prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background image
47px to the right (#home width 46px + 1px line divider)
• #next {left:129px;width:43px;}- Positioned 129px to the right (start of #prev is 63px +
#prev width 43px + extra space), and the width is 43px.
• #next {background:url('img_navsprites.gif') -91px 0;} - Defines the background image
91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line
divider )

Image Sprites - Hover Effect

Now we want to add a hover effect to our navigation list.

Tip: The :hover selector can be used on all elements, not only on links.

Our new image ("img_navsprites_hover.gif") contains three navigation images and three
images to use for hover effects:
Because this is one single image, and not six separate files, there will be no loading
delay when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example

#home a:hover {
background: url('img_navsprites_hover.gif') 0 -45px;
}

#prev a:hover {
background: url('img_navsprites_hover.gif') -47px -45px;
}

#next a:hover {
background: url('img_navsprites_hover.gif') -91px -45px;
}

Example explained:

• #home a:hover {background: transparent url('img_navsprites_hover.gif') 0 -45px;} -


For all three hover images we specify the same background position, only 45px
further down

CSS Attribute Selectors

Style HTML Elements With Specific Attributes

It is possible to style HTML elements that have specific attributes or attribute values.

CSS [attribute] Selector

The [attribute] selector is used to select elements with a specified attribute.

The following example selects all <a> elements with a target attribute:
Example

a[target] {
background-color: yellow;
}

CSS [attribute="value"] Selector

The [attribute="value"] selector is used to select elements with a specified attribute and
value.

The following example selects all <a> elements with a target="_blank" attribute:

Example

a[target="_blank"] {
background-color: yellow;
}

CSS [attribute~="value"] Selector

The [attribute~="value"] selector is used to select elements with an attribute value containing
a specified word.

The following example selects all elements with a title attribute that contains a space-
separated list of words, one of which is "flower":

Example

[title~="flower"] {
border: 5px solid yellow;
}

The example above will match elements with title="flower", title="summer flower", and
title="flower new", but not title="my-flower" or title="flowers".

CSS [attribute|="value"] Selector

The [attribute|="value"] selector is used to select elements with the specified attribute starting
with the specified value.

The following example selects all elements with a class attribute value that begins with "top":

Note: The value has to be a whole word, either alone, like class="top", or followed by a
hyphen( - ), like class="top-text"!
Example

[class|="top"] {
background: yellow;
}

CSS [attribute^="value"] Selector

The [attribute^="value"] selector is used to select elements whose attribute value begins with
a specified value.

The following example selects all elements with a class attribute value that begins with "top":

Note: The value does not have to be a whole word!

Example

[class^="top"] {
background: yellow;
}

CSS [attribute$="value"] Selector

The [attribute$="value"] selector is used to select elements whose attribute value ends with a
specified value.

The following example selects all elements with a class attribute value that ends with "test":

Note: The value does not have to be a whole word!

Example

[class$="test"] {
background: yellow;
}

CSS [attribute*="value"] Selector

The [attribute*="value"] selector is used to select elements whose attribute value contains a
specified value.

The following example selects all elements with a class attribute value that contains "te":

Note: The value does not have to be a whole word!


Example

[class*="te"] {
background: yellow;
}

Styling Forms

The attribute selectors can be useful for styling forms without class or ID:

Example

input[type="text"] {
width: 150px;
display: block;
margin-bottom: 10px;
background-color: yellow;
}

input[type="button"] {
width: 120px;
margin-left: 35px;
display: block;
}
LESSON 17

LEARNING OBJECTIVES:

At the end of this lesson, the students should be able to:


➢ Design form and form elements using CSS.
➢ Draw and explain the qualities of a good website layout.
➢ Identify units used in CSS coding.
➢ Apply CSS specificity in web design.

CSS Forms

Styling Input Fields

Use the width property to determine the width of the input field:

Example

input {
width: 100%;
}

The example above applies to all <input> elements. If you only want to style a specific input
type, you can use attribute selectors:

• input[type=text] - will only select text fields


• input[type=password] - will only select password fields
• input[type=number] - will only select number fields
• etc..

Padded Inputs

Use the padding property to add space inside the text field.

Tip: When you have many inputs after each other, you might also want to add some margin,
to add more space outside of them:
Example

input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}

Note that we have set the box-sizing property to border-box. This makes sure that the padding
and eventually borders are included in the total width and height of the elements.
Read more about the box-sizing property in our CSS Box Sizing chapter.

Bordered Inputs

Use the border property to change the border size and color, and use the border-
radius property to add rounded corners:

Example

input[type=text] {
border: 2px solid red;
border-radius: 4px;
}

If you only want a bottom border, use the border-bottom property:

input[type=text] {
border: none;
border-bottom: 2px solid red;
}
Colored Inputs

Use the background-color property to add a background color to the input, and
the color property to change the text color:

Example

input[type=text] {
background-color: #3CBC8D;
color: white;
}

Focused Inputs

By default, some browsers will add a blue outline around the input when it gets focus (clicked
on). You can remove this behavior by adding outline: none; to the input.

Use the :focus selector to do something with the input field when it gets focus:

Input with icon/image

If you want an icon inside the input, use the background-image property and position it with
the background-position property. Also notice that we add a large left padding to reserve the
space of the icon:

Example

input[type=text] {
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding-left: 40px;
}

Animated Search Input

In this example we use the CSS transition property to animate the width of the search input
when it gets focus.

Example

input[type=text] {
transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
width: 100%;
}

Styling Textareas

Tip: Use the resize property to prevent textareas from being resized (disable the "grabber" in
the bottom right corner):

Example

textarea {
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}

Styling Select Menus


Styling Input Buttons

Example

input[type=button], input[type=submit], input[type=reset] {


background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}

/* Tip: use width: 100% for full-width buttons */

CSS Counters

CSS counters are "variables" maintained by CSS whose values can be incremented by CSS
rules (to track how many times they are used). Counters let you adjust the appearance of
content based on its placement in the document.
Automatic Numbering With Counters

CSS counters are like "variables". The variable values can be incremented by CSS rules
(which will track how many times they are used).

To work with CSS counters we will use the following properties:

• counter-reset - Creates or resets a counter


• counter-increment - Increments a counter value
• content - Inserts generated content
• counter() or counters() function - Adds the value of a counter to an element

To use a CSS counter, it must first be created with counter-reset.

The following example creates a counter for the page (in the body selector), then increments
the counter value for each <h2> element and adds "Section <value of the counter>:" to the
beginning of each <h2> element:

Example

body {
counter-reset: section;
}

h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}

Nesting Counters

The following example creates one counter for the page (section) and one counter for each
<h1> element (subsection). The "section" counter will be counted for each <h1> element
with "Section <value of the section counter>.", and the "subsection" counter will be counted
for each <h2> element with "<value of the section counter>.<value of the subsection
counter>":

Example

body {
counter-reset: section;
}

h1 {
counter-reset: subsection;
}
h1::before {
counter-increment: section;
content: "Section " counter(section) ". ";
}

h2::before {
counter-increment: subsection;
content: counter(section) "." counter(subsection) " ";
}

A counter can also be useful to make outlined lists because a new instance of a counter is
automatically created in child elements. Here we use the counters() function to insert a string
between different levels of nested counters:

Example

ol {
counter-reset: section;
list-style-type: none;
}

li::before {
counter-increment: section;
content: counters(section,".") " ";
}

CSS Counter Properties

CSS Website Layout

Website Layout

A website is often divided into headers, menus, content and a 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

.header {
background-color: #F1F1F1;
text-align: center;
padding: 20px;
}

Navigation Bar

A navigation bar contains a list of links to help visitors navigating through your website:

Example

/* The navbar container */


.topnav {
overflow: hidden;
background-color: #333;
}

/* Navbar links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

/* Links - change color on hover */


.topnav a:hover {
background-color: #ddd;
color: black;
}

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 (often used for mobile browsers)


• 2-column (often used for tablets and laptops)
• 3-column layout (only used for desktops)

We will create a 3-column layout, and change it to a 1-column layout on smaller screens:

Example

/* Create three equal columns that floats next to each other */


.column {
float: left;
width: 33.33%;
}

/* Clear floats after the columns */


.row:after {
content: "";
display: table;
clear: both;
}

/* Responsive layout - makes the three columns stack on top of each other instead of
next to each other on smaller screens (600px wide or less) */
@media screen and (max-width: 600px) {
.column {
width: 100%;
}
}

Tip: To create a 2-column layout, change the width to 50%. To create a 4-column layout,
use 25%, etc.
Tip: A more modern way of creating column layouts, is to use CSS Flexbox. However, it is
not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use
floats (as shown above).

Unequal Columns

The main content is the biggest and the most important part of your site.

It is common with unequal column widths, so that most of the space is reserved for the main
content. The side content (if any) is often used as an alternative navigation or to specify
information relevant to the main content. Change the widths as you like, only remember that
it should add up to 100% in total:

Example

.column {
float: left;
}

/* Left and right column */


.column.side {
width: 25%;
}

/* Middle column */
.column.middle {
width: 50%;
}

/* 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.side, .column.middle {
width: 100%;
}
}

Footer

The footer is placed at the bottom of your page. It often contains information like copyright
and contact info:

Example

.footer {
background-color: #F1F1F1;
text-align: center;
padding: 10px;
}
CSS Units

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as width, margin, padding, font-size, etc.

Length is a number followed by a length unit, such as 10px, 2em, etc.

A whitespace cannot appear between the number and the unit. However, if the value is 0,
the unit can be omitted.

For some CSS properties, negative lengths are allowed.

There are two types of length units: absolute and relative.

Absolute Lengths

The absolute length units are fixed and a length expressed in any of these will appear as
exactly that size.

Absolute length units are not recommended for use on screen, because screen sizes vary so
much. However, they can be used if the output medium is known, such as for print layout.

* Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one device pixel
(dot) of the display. For printers and high resolution screens 1px implies multiple device
pixels.

Relative Lengths

Relative length units specify a length relative to another length property. Relative length units
scales better between different rendering mediums.
Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.

Browser Support

The numbers in the table specify the first browser version that fully supports the length unit.

CSS Specificity

What is Specificity?

If there are two or more conflicting CSS rules that point to the same element, the browser
follows some rules to determine which one is most specific and therefore wins out.
Think of specificity as a score/rank that determines which style declarations are ultimately
applied to an element.

The universal selector (*) has low specificity, while ID selectors are highly specific!

Note: Specificity is a common reason why your CSS-rules don't apply to some elements,
although you think they should.

Specificity Hierarchy

Every selector has its place in the specificity hierarchy. There are four categories which
define the specificity level of a selector:

Inline styles - An inline style is attached directly to the element to be styled. Example: <h1
style="color: #ffffff;">.

IDs - An ID is a unique identifier for the page elements, such as #navbar.

Classes, attributes and pseudo-classes - This category includes .classes, [attributes] and
pseudo-classes such as :hover, :focus etc.

Elements and pseudo-elements - This category includes element names and pseudo-
elements, such as h1, div, :before and :after.

How to Calculate Specificity?

Memorize how to calculate specificity!

Start at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class
or pseudo-class, add 1 for each element name or pseudo-element.

Consider these three code fragments:

Example

A: h1
B: #content h1
C: <div id="content"><h1 style="color: #ffffff">Heading</h1></div>

The specificity of A is 1 (one element)


The specificity of B is 101 (one ID reference and one element)
The specificity of C is 1000 (inline styling)

Since 1 < 101 < 1000, the third rule (C) has a greater level of specificity, and therefore will be
applied.
Specificity Rules

Equal specificity: the latest rule counts - If the same rule is written twice into the external
style sheet, then the lower rule in the style sheet is closer to the element to be styled, and
therefore will be applied:

Example

h1 {background-color: yellow;}
h1 {background-color: red;}

the latter rule is always applied.

ID selectors have a higher specificity than attribute selectors - Look at the following
three code lines:

Example

div#a {background-color: green;}


#a {background-color: yellow;}
div[id=a] {background-color: blue;}

the first rule is more specific than the other two, and will be applied.

Contextual selectors are more specific than a single element selector - The embedded
style sheet is closer to the element to be styled. So in the following situation

Example

From external CSS file:


#content h1 {background-color: red;}

In HTML file:
<style>
#content h1 {
background-color: yellow;
}
</style>

the latter rule will be applied.

A class selector beats any number of element selectors - a class selector such as .intro
beats h1, p, div, etc:

Example
.intro {background-color: yellow;}
h1 {background-color: red;}

The universal selector and inherited values have a specificity of 0 - *, body * and similar
have a zero specificity. Inherited values also have a specificity of 0.
ASSESSMENT – GRADING RUBRICS

CATEGORY Excellent Good Satisfactory Needs Improvement


Content All information Almost all the Almost all of the There are several
provided by the information information inaccuracies in the
provided by the content provided by
student on the web student on the web
provided by the the students OR
site is accurate and site is accurate and student on the many of the
all the requirements all requirements of web site is requirements were
of the assignment the assignment accurate and not met. Not
have been met. In have been met. Or almost all of the enough content,
all the information very incomplete.
other words, there is is accurate but not
requirements
sufficient content in all of the have been met.
this website to learn requirements of the If there is little
about the topic and assignment were information on
complete a research met. Information is the website,
not complete.
assignment. then it is
satisfactory. If
researchers
cannot find
what they need
on your
website, it is
satisfactory.
Learning of The student has an The student has a The student has a Student did not
Material exceptional good fair understanding appear to learn
understanding of the understanding of of the material much from this
material included in the the material included in the site. project. Cannot
site and where to find included in the site. Can easily answer answer most
additional information. Can easily answer most questions questions about the
Can easily answer questions about about the content content and the
questions about the the content and and procedures procedures used to
content and procedures procedures used to used to make the make the web site.
used to make the web make the web site. web site.
site.
Links All links point to high Almost all links Most links point to Less than 1/2 of the
(content) quality, up-to-date, point to high high quality, up-to- links point to high
credible sites in the quality, up-to-date, date, credible sites quality, up-to-date,
bibliography. AND all the credible sites in the in the bibliography. credible sites in the
links, including links to bibliography. Or Or there are too bibliography. Or
their own pages, work. there aren't many few links. AND there are barely any
links. AND many or some of the links, links. AND few of
most of the links, including links to the links, including
including links to their own pages, links to their own
their own pages, work. pages, work or you
work. have very few
pages.
Graphics Graphics are related to Graphics are Graphics are Graphics seem
the theme/purpose of related to the related to the randomly chosen,
the site, are thoughtfully theme/purpose of theme/purpose of are of low quality,
cropped, are of high the site, are of the site, and are of OR distract the
quality and enhance good quality and good quality. There reader. Many
reader interest or enhance reader may be a few images are broken.
understanding. There interest or broken images.
are no broken images. understanding.
There are no
broken images.
Layout The web site has an The web pages The web pages The web pages are
exceptionally attractive have an attractive have a usable cluttered looking or
and usable layout. It is and usable layout. layout, but may confusing. It is often
easy to locate all It is easy to locate appear busy or difficult to locate
important elements. all important boring. It is easy to important elements.
White space, graphic elements. locate most of the
elements and/or important
alignment are used elements.
effectively to organize
material.
Navigation Links for navigation are Links for navigation Links for navigation Some links do not
clearly labeled, are clearly labeled, take the reader take the reader to
consistently placed, allow the reader to where s/he expects the sites described.
allow the reader to easily move from a to go, but some A user typically
easily move from a page page to related needed links seem feels lost.
to related pages pages (forward and to be missing. A
(forward and back), and back), and internal user sometimes
take the reader where links take the gets lost.
s/he expects to go. A reader where s/he
user does not become expects to go. A
lost. user rarely
becomes lost.
Work Ethic Students always use Students usually Students usually Students do not use
classroom project time use classroom use classroom classroom project
well. Conversations are project time well. project time well, time well OR
primarily focused on the Most conversations but occasionally typically are
project and things are focused on the distract others from disruptive to the
needed to get the work project and things their work. work of others.
done and are held in a needed to get the
manner that typically work done and are
does not disrupt others. held in a manner
that typically does
not disrupt others.
Cooperative Partners show respect Partners show Partners show Partners argue or
Work for one another's ideas, respect for one respect for one are disrespectful of
divide the work fairly, another's ideas another's ideas and other's ideas and
and show a commitment and divide the work divide the work input. Criticism is
to quality work and fairly. There is fairly. There is little not constructive nor
support for each other. commitment by evidence of a is support offered.
some members commitment toward The work is mostly
toward quality work quality work in the done by one or two
and support of one group or there people.
another. There were some
may have been a arguments.
few arguments but
they were handled
well.
Color Colors of background, Colors of Colors of Colors of
Choices fonts, unvisited and background, fonts, background, fonts, background, fonts,
visited links form a unvisited and unvisited and unvisited and
pleasing palette, do not visited links do not visited links do not visited links make
detract from the content, detract from the detract from the the content hard to
content, and are content.
and are consistent consistent across read or otherwise
across pages. pages. distract the reader.
Background Background is Background is Background is Background
exceptionally attractive, attractive, consistent across detracts from the
consistent across pages, consistent across pages and does readability of the
adds to the theme or pages, adds to the not detract from site.
purpose of the site, and theme or purpose readability.
does not detract from of the site, and
readability. does not detract
from readability.
Fonts The fonts are consistent, The fonts are The fonts are A wide variety of
easy to read and point consistent, easy to consistent and fonts, styles and
size varies appropriately read and point size point size varies point sizes was
for headings and text. varies appropriately for used.
Use of font styles (italic, appropriately for headings and text.
bold, underline) is used headings and text.
consistently and
improves readability.
Interest The author has made an The author has The author has put The author has
exceptional attempt to tried to make the lots of information provided only the
make the content of this content of this web in the web site but minimum amount of
web site interesting to site interesting to there is little information and has
the people for whom it is the people for evidence that the not transformed the
intended. whom it is person tried to information to make
intended. present the it more interesting
information in an to the audience
interesting way. (e.g., has only
provided a list of
links to the content
of others).
Copyright Fair use guidelines are Fair use guidelines Fair use guidelines Borrowed materials
followed with clear, are followed with are followed with are not properly
easy-to-locate and clear, easy-to- clear, easy-to- documented OR
accurate citations for all locate and locate and material was
borrowed material. No accurate citations accurate citations borrowed without
material is included from for almost all for most borrowed permission from a
websites that state that borrowed material. material. No site that requires
permission is required No material is material is included permission
unless permission has included from from websites that
been obtained. websites that state state that
that permission is permission is
required unless required unless
permission has permission has
been obtained. been obtained.
Contact Every web page Almost all web Most (75-80%) web Several web pages
Information contains a statement of pages contain a pages contain a do not contain a
authorship, school statement of statement of statement of
name, and date of authorship, school authorship, school authorship, school
publication/date last name, and date of name, and date of name, and/or date
edited. publication/date publication/date of publication/date
last edited. last edited. last edited.
Spelling and There are either no There are a few There are several There are maybe
Grammar spelling or grammatical spelling and/or spelling and/or many spelling
errors, but there may be grammatical errors grammatical errors and/or grammatical
one or two very minor in the entire site. in the entire site. errors in the entire
spelling and/or site.
grammatical errors in
the entire site.
Group member names __________________________ Date _____________

Website Design Grading Sheet


Category Excellent Good Satisfactory Needs Improvement
Content 16 12 8 4
Learning of Material 16 12 8 4
Link (content) 12 9 6 3
Graphics 12 9 6 3
Layout 12 9 6 3
Navigation 12 9 6 3
Work Ethic 12 9 6 3
Cooperative Work 12 9 6 3
Color Choices 4 3 2 1
Background 4 3 2 1
Fonts 4 3 2 1
Interest 6 4 2 1
Copyright 4 3 2 1
Contact Information 4 3 2 1
Spelling and Grammar 4 3 2 1

Total Points Possible = 134 Your score is ________

Scoring Scale
134 128 121 120 114 108 107 100 94 93 87 81
Excellent Good Satisfactory Needs Improvement
A B C D
REFERENCES

1. CSS Tutorial - Tutorialspoint. (2020). Retrieved 15 July 2020, from


https://www.tutorialspoint.com/css/index.htm

2. CSS Tutorial. (2020). Retrieved 15 July 2020, from


https://www.w3schools.com/css/default.asp

3. Dean, J. (2019). Web Programming w/ HTML5, CSS & Javascript


Burlington,MA: Jones & Barlett Learning

4. Frain, B. (2015). Responsive Web Design with HTML5 and CSS3 2nd Ed.
Birmingham: Packt Publishing
5. HTML Tutorial - Tutorialspoint. (2020). Retrieved 15 July 2020, from
https://www.tutorialspoint.com/html/index.htm
6. HTML Tutorial. (2020). Retrieved 15 July 2020, from
https://www.w3schools.com/html/default.asp

7. Macaulay, M. (2018). Introduction to Web Interaction w/ HTML and CSS.


New York: CRC Press Taylor & Francis Group, LLC

8. Robbins, J.N. (2018). Learning Web Design 5th Ed.. Canada: O’Rielly
Media Inc.

You might also like