Skip to content

HTML - tutorial

Editors

You can use any text editor or notepads like Brackets, or use frontend-editor.

Brackets is a free, open-source code editor that is designed specifically for web development. It was developed by Adobe and released in 2014, and it has since gained popularity among web developers for its ease of use and integration with other web development tools. Brackets includes features such as live preview of changes, syntax highlighting, auto-completion, and support for HTML, CSS, and JavaScript, as well as a number of extensions that allow developers to customize the editor to their specific needs. Brackets is available for Windows, Mac, and Linux.

Basic

An HTML document must begin with a document type declaration, which is written as <!DOCTYPE html>.

The HTML document starts with the <html> tag and ends with the </html> tag.

The content that is visible to the user is contained within the <body> and </body> tags.

The !DOCTYPE Declaration

The <!DOCTYPE> declaration specifies the document type of an HTML page, enabling browsers to render the page correctly.

It should appear only once at the top of the page, before any other HTML tags.

The <!DOCTYPE> declaration is case-insensitive.

The <!DOCTYPE> declaration for HTML5 is:

<!DOCTYPE html>

Headings

HTML headings are created using the <h1> to <h6> tags, with <h1> representing the most important heading and <h6> representing the least important.

<h1>This is heading 1</h1>  
<h2>This is heading 2</h2>  
<h3>This is heading 3</h3>

Paragraphs

<p>This is a paragraph.</p>  
<p>This is another paragraph.</p>
<a href="whateverlink">This is a link</a>

The href attribute specifies the destination of a link.

Attributes are utilized to furnish supplementary details about HTML elements.

Images

HTML images are created using the <img> tag.

Attributes such as src, alt, width, and height are used to provide additional details about the image.

<img src="image link" alt="decription" width="104" height="142">

Elements

HTML elements refer to everything between the opening and closing tags, including the tags themselves:

<tag>Content...</tag>

HTML elements can be nested, which means that an element can contain other elements, and all HTML documents are made up of nested HTML elements.

It is important to always include the closing tag when working with nested HTML elements.

Empty HTML elements contain no content, and the <br> tag, which defines a line break, is an example of an empty element that doesn't require a closing tag.

HTML tags are not case-sensitive, meaning that <P> and <p> are interchangeable. However, lowercase tags are recommended for stricter document types like XHTML according to HTML standards.

Attributes

All HTML elements can have attributes, which provide additional information about the elements. Attributes are always specified in the start tag and usually come in name/value pairs, like name="value".

href

The href attribute is used in the <a> tag to specify the URL of the page that the link goes to.

src

The src attribute is used in the <img> tag to specify the path to the image to be displayed. There are two ways to specify the URL: absolute and relative.

width and height

The width and height attributes are used in the <img> tag to specify the width and height of the image (in pixels).

alt

The alt attribute is required in the <img> tag and specifies alternate text for an image if the image cannot be displayed.

style

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

lang

The lang attribute should always be included inside the <html> tag to declare the language of the web page.

title

The title attribute defines extra information about an element and is displayed as a tooltip when the user mouses over the element.

Empty Elements

HTML elements with no content are called empty elements. For example, the <br> tag is an empty element without a closing tag.

HTML Attribute Best Practices

It is best to always use lowercase attributes and to quote attribute values with double quotes. In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes.

Headings

HTML headings are used to display titles or subtitles on a webpage. They are defined with the <h1> to <h6> tags, and are automatically given some white space (a margin) before and after them by browsers. Search engines use headings to index the structure and content of web pages, and users often skim a page by its headings. Thus, it is important to use headings to show the document structure. Each HTML heading has a default size, but you can specify the size of any heading using the style attribute and the CSS font-size property.

Paragraphs

HTML paragraphs are blocks of text that start on a new line, and browsers automatically add some white space (a margin) before and after each paragraph.

Displaying HTML content can vary depending on screen size and window size, and adding extra spaces or lines in HTML code will not change how it is displayed. The browser will automatically remove any extra spaces and lines when the page is displayed.

Horizontal rules, defined by the <hr> tag, create a thematic break in an HTML page and are often displayed as a horizontal line to separate content or indicate a change.

The <br> element creates a line break (a new line) without starting a new paragraph, useful for breaking lines within a paragraph or adding space between lines.

The <pre> element defines preformatted text and displays it in a fixed-width font, preserving both spaces and line breaks. This is useful for displaying code or text that needs to maintain a specific layout.

Style attributes

To add styles to an HTML element, such as color, font, size, and more, you can use the style attribute.

The syntax of the style attribute in HTML is as follows:

<tag style="property:value;">

Tag can be body, div, paragraph, span...

  • background-color 
  • color property defines the text color
  • font-family 
  • font-size property defines the text size for an HTML element.
  • horizontal text alignment  text-align 

Formatting elements

Special types of text can be displayed using formatting elements.

<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

<b> tag specifies bold text without any additional significance, while the HTML <strong> tag indicates text with strong importance and is typically displayed in bold.

<i> tag signifies a section of text in an alternate voice or mood and is usually displayed in italic. In contrast, the HTML <em> tag emphasizes the text and is also typically displayed in italic.

Note that the <i> tag is frequently used to denote technical terms, foreign phrases, thoughts, or names of vessels, while the <em> tag highlights words with verbal stress when read by a screen reader.

<small> tag defines smaller text, whereas the HTML <mark> tag identifies text that should be marked or highlighted.

<del> tag represents text that has been removed from a document, usually displayed with a line through it. The HTML <ins> tag indicates text that has been inserted into a document and is usually underlined by browsers.

<sub> tag is used for subscript text, which appears half a character below the normal line and may be rendered in a smaller font. Subscript text is frequently employed in chemical formulas, such as H2O. The HTML <sup> tag is used for superscript text, which appears half a character above the normal line and may also be rendered in a smaller font. Superscript text is frequently used for footnotes, such as WWW[1].

Quotation and Citation Elements

  • <blockquote>,<q>, <abbr>, <address>, <cite>, and <bdo>

<blockquote> element denotes a quoted section from another source, and browsers typically indent such elements.

<q> tag represents a brief quotation, with quotation marks added by browsers by default.

To indicate an abbreviation or acronym, such as "HTML," "CSS," the HTML <abbr> tag can be used. This can be valuable information for browsers, translation systems, and search engines. Consider utilizing the global title attribute to display the abbreviation/acronym's explanation when hovering over the element.

<address> tag specifies the author/owner's contact information for a document or article, including email address, URL, physical address, phone number, social media handle, and so on. The text within the <address> element typically appears in italics, and browsers always insert a line break before and after the element.

<cite> tag specifies the name of a creative work (e.g., a book, poem, song, movie, painting, sculpture, etc.), not an individual's name. The text within the <cite> element usually appears in italics.

The term BDO refers to Bi-Directional Override. The HTML <bdo> tag is used to override the current text direction.

Comments

Although comments are not visible in the browser, they can provide documentation for your HTML source code. Comments allow you to include notifications and reminders within your HTML code and can even be used to conceal content temporarily. It is possible to hide multiple lines by enclosing the text between the <!-- and --> markers.

Comments are also a valuable tool for debugging HTML, as you can comment out individual lines of code to isolate and locate errors. Additionally, comments can be used to conceal sections within the middle of the HTML code.

To add comments to your HTML source code, use the following syntax:

<!-- Your comment goes here -->

Colors

HTML provides various ways to specify colors for different elements on a web page.

These include - predefined color names, - RGB, - HEX, - HSL, - RGBA, and - HSLA values.

There are [[ 140 standard colors ]] names that can be used to set a color for HTML elements.

Some examples of these color names include "red," "blue," "green," "yellow," "purple," and "black." These names are easily recognizable and can be used to set the color for various elements, such as the background, text, and borders.

In addition to the color names, you can also specify a color using RGB values. RGB stands for Red, Green, and Blue, and each color value can range from 0 to 255. For example, the RGB value for pure red is "rgb(255, 0, 0)." Another way to represent colors is with HEX values, which use a combination of six letters and numbers to specify a color. For example, "#FF0000" represents pure red.

HTML also supports HSL (Hue, Saturation, and Lightness) and HSLA (Hue, Saturation, Lightness, and Alpha) color values. These values define a color by specifying its hue, saturation, and lightness or alpha transparency. The HSL and HSLA values provide more flexibility when it comes to defining color shades and tones.

RGB (Red, Green, Blue) color values are a way of representing colors in digital devices that use light sources. These sources emit red, green, and blue light, which can be combined to create a wide range of colors. The RGB color model is widely used in HTML and other digital mediums to represent colors.

An RGB value is represented by three values, one for each of the red, green, and blue color channels. These values range from 0 to 255, with 0 representing the absence of the color and 255 representing the highest intensity of the color. By varying the values of these three channels, you can create a wide range of colors, including black and white.

Shades of gray are often represented by RGB values with equal values for all three color channels, such as rgb(60, 60, 60), rgb(140, 140, 140), and rgb(180, 180, 180).

RGBA (Red, Green, Blue, Alpha) color values are an extension of RGB color values that include an alpha channel for specifying opacity. The alpha channel specifies the level of transparency for the color, with 0.0 being fully transparent and 1.0 being fully opaque. An RGBA value is represented by four values, one for each of the RGB channels and one for the alpha channel.

Hexadecimal colors, also known as HEX colors, are a way to represent colors in HTML using a combination of six hexadecimal digits. Each digit represents a value between 0 and 15, and the six digits together represent the intensity of red, green, and blue in the color.

HSL stands for hue, saturation, and lightness. It is an alternative way of specifying colors in HTML that allows for greater control over the appearance of a color.

HSL Color Values In HSL, a color is specified using hue, saturation, and lightness 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, with 0% being gray and 100% being the full color. Lightness is also a percentage value, with 0% being black and 100% being white.

Using HSL, it is possible to create many shades of a color by adjusting the hue, saturation, and lightness values. For example, to create a range of blue shades, you can vary the hue value from 200 to 250, while keeping saturation and lightness constant.

HSLA Color Values HSLA color values are an extension of HSL color values, with an added Alpha channel that specifies the opacity of a color.

An HSLA color value is specified with:

hsla(hue, saturation, lightness, alpha)

The alpha value is a number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being not transparent at all. The HSLA color format is useful when you want to apply a semi-transparent color to an element, such as a background or text color.

In addition to RGB, HEX, HSL, and HSLA color values, HTML also supports 140 standard color names. These color names can be used to specify the color of an element in HTML, and include common colors such as red, green, blue, black, and white.

CSS

🧿 CSS - z-class

Cascading Style Sheets, commonly known as CSS, is a formatting language used to control the layout and design of web pages. CSS offers a range of features that enable users to modify the appearance of text, spacing, positioning, background colors, and images, as well as display options for different devices and screen sizes.

The term "cascading" indicates that styles applied to a parent element will also affect all child elements within that parent. For example, setting the text color of the body element to "blue" will result in all text elements within the body inheriting that color, unless specified otherwise.

CSS can be added to HTML documents in three ways: inline, internal, and external. Inline CSS applies a unique style to a single HTML element, using the style attribute of that element. Internal CSS defines a style for a single HTML page and is declared in the <head> section of the HTML document within a <style> element. External style sheets are used to define styles for multiple HTML pages and are linked to the <head> section of each HTML document using a <link> element.

The most common method for adding CSS is through external style sheets as it allows for a centralized style file that can be modified to update the appearance of an entire website. However, inline and internal styles can be useful for testing and demonstrating individual styles.

CSS properties can be used to modify various aspects of HTML elements, such as the color, font family, font size, borders, padding, and margins. External style sheets can be referenced with a full URL or a relative path to the current web page.

<link rel="stylesheet" href="https://www.w3schools.com/html/styles.css">

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

Summary

  • Use the HTML style attribute for inline styling
  • Use the HTML <style> element to define internal CSS
  • <link> element to refer to an external CSS file
  • <head> element to store <style> and <link> elements
  • color property for text colors
  • font-family property for text fonts
  • font-size property for text sizes
  • border property for borders
  • padding property for space inside the border
  • margin property for space outside the border

HTML links are hyperlinks that allow users to navigate between web pages. HTML links are created using the <a> tag, which stands for anchor tag.

The most important attribute of the <a> tag is the href attribute, which indicates the destination of the link. The destination is specified as a URL, which stands for Uniform Resource Locator. URLs can be absolute or relative.

Absolute URLs contain the entire address, including the protocol (http, https, ftp, etc.) and the domain name.

Relative URLs only specify a portion of the address, such as the file name or folder. Relative URLs are relative to the current page, and can be used to link to pages within the same website. For example, a relative URL for the page would be /folder/file.html

HTML links are displayed as underlined and clickable text by default. However, the appearance of the link can be customized using CSS.

HTML links can also be used to create links to email addresses, files, and other resources. To create a link to an email address, the href attribute should begin with "mailto:" followed by the email address. To create a link to a file, the href attribute should specify the file path and name.

Links can also be targeted to open in a new window or tab using the target attribute. The target attribute should be set to "_blank" to open the link in a new window or tab.

If you want to use an image as a hyperlink, simply enclose the <img> tag within the <a> tag.

However, if you wish to use an HTML button as a hyperlink, you need to include some JavaScript code.

JavaScript enables you to determine the action that occurs when specific events, such as clicking a button, take place.

The title attribute provides supplementary information about an element. Typically, this information appears as a tooltip text when the mouse hovers over the element.

Summary

  • Use the <a> element to define a link
  • Use the href attribute to define the link address
  • Use the target attribute to define where to open the linked document
  • Use the <img> element (inside <a>) to use an image as a link
  • Use the mailto: scheme inside the href attribute to create a link that opens the user's email program

When using HTML links, the color of the link text changes based on whether it has been visited, is unvisited, or is currently active.

The default appearance of links in all browsers is as follows:

An unvisited link is blue and underlined. A visited link is purple and underlined. An active link is red and underlined.

Using HTML links, it's possible to create bookmarks that allow readers to quickly navigate to specific parts of a web page.

Creating a bookmark in HTML is simple - just specify a unique ID attribute for the HTML element that you want to link to.

Example:

Use the id attribute to create a bookmark. Add a link to the bookmark ("Jump to Chapter 4"), from within the same page. Or add a link to a bookmark on another page.

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

Images

Improving the look and feel of a web page can be achieved by adding images.

HTML Images Syntax

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

Images are not actually inserted into a web page but are linked to web pages. The <img> tag creates a space to hold the referenced image.

The <img> tag is an empty tag, which means it contains only attributes and does not have a closing tag.

Two attributes are required for the <img> tag:

  • src: Specifies the path to the image.
  • alt: Specifies alternate text for the image.

src

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

Note: When a web page loads, the browser retrieves the image from the web server and inserts it into the page. Therefore, ensure that the image remains in the same position relative to the web page. Otherwise, visitors will see a broken link icon. If the browser cannot find the image, the broken link icon and the alt text are displayed.

alt

The alt attribute is also required and provides an alternative text for an image in case the user cannot view it.

The alt attribute's value should describe the image. If a browser cannot find an image, it will display the value of the alt attribute.

Image Size - Width and Height

You can use the style attribute or the width and height attributes to specify the width and height of an image. The width and height attributes define the image's width and height in pixels.

Note: Always specify the width and height of an image. If they are not specified, the web page may flicker while the image loads.

Width and Height, or Style?

The width, height, and style attributes are all valid in HTML. However, it is recommended to use the style attribute to prevent style sheets from changing the image size.

Images in Another Folder

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

Images on Another Server/Website

To point to an image on another server, you must specify the absolute (full) URL in the src attribute.

Notes on External Images: External images may be under copyright. Without permission, you may be violating copyright laws. Also, external images may be removed or changed unexpectedly.

Animated Images

HTML supports animated GIFs.

Image Floating

Use the CSS float property to allow an image to float to the right or left of a text.

Summary

  • Use the HTML <img> element to define an image
  • Use the HTML src attribute to define the URL of the image
  • Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed
  • Use the HTML width and height attributes or the CSS width and height properties to define the size of the image
  • Use the CSS float property to let the image float to the left or to the right

Note: Loading large images takes time, and can slow down your web page. Use images carefully.

Common Image Formats - supported in Chrome, Edge, Firefox, Safari, Opera

Abbreviation File Format File Extension
APNG Animated Portable Network Graphics .apng
GIF Graphics Interchange Format .gif
ICO Microsoft Icon .ico, .cur
JPEG Joint Photographic Expert Group image .jpg, .jpeg, .jfif, .pjpeg, .pjp
PNG Portable Network Graphics .png
SVG Scalable Vector Graphics .svg

Image Maps

With HTML image maps, you can create clickable areas on an image. The <map> tag is used to define an image map, which is an image with clickable areas that are defined using one or more <area> tags.

To create an image map, you need an image and HTML code that describes the clickable areas. Insert the image using the <img> tag and add a usemap attribute with a value that starts with a hash tag # followed by the name of the image map. Then, create a <map> element that is linked to the image using the required name attribute.

To define clickable areas, add <area> elements with a shape attribute that defines the shape of the area, which can be rect (for a rectangular region), circle (for a circular region), poly (for a polygonal region), or default (for the entire region). Additionally, you must define coordinates to place the clickable area onto the image.

For shape="rect", you must define pairs of coordinates for the x-axis and y-axis. For shape="circle", you must locate the coordinates of the center of the circle and specify its radius. For shape="poly", you must provide the x and y coordinates for all edges.

You can also use JavaScript to trigger a function when a clickable area is clicked. Add a click event to the <area> element to execute a JavaScript function.

Summary

  • Use the HTML <map> element to define an image map
  • Use the HTML <area> element to define the clickable areas in the image map
  • Use the HTML usemap attribute of the <img> element to point to an image map

Image Tags

Tag Description
<img> Defines an image
<map> Defines an image map
 <area> Defines a clickable area inside an image map
<picture> Defines a container for multiple image resources

Background Images

To add a background image to an HTML element, you can use the HTML style attribute along with the CSS background-image property. This can be specified for almost any HTML element. Alternatively, you can also specify the background image in the <style> element within the <head> section.

If you want the background image to be applied to the entire page, you must set it on the <body> element.

If the background image is smaller than the element, it will repeat itself both horizontally and vertically until it fills the element. However, you can prevent the image from repeating by setting the background-repeat property to no-repeat.

To make the background image cover the entire element, set the background-size property to cover. You can ensure that the entire element is always covered by setting the background-attachment property to fixed, which prevents the image from stretching and preserves its original proportions.

Alternatively, you can set the background-size property to 100% 100% if you want the background image to stretch to fit the entire element.

Picture Element

The HTML <picture> element provides a way to display different images based on device or screen size, offering greater flexibility in specifying image resources.

Inside the <picture> element, you can include one or more <source> elements, each pointing to different images through the srcset attribute. This enables the browser to select the most appropriate image based on the current view and device.

Additionally, each <source> element can have a media attribute that specifies the optimal conditions for that image.

It's important to note that the <img> element should always be included as the last child element of the <picture> element. This allows browsers that don't support the <picture> element or don't find any matching <source> tags to use the <img> element as a fallback.

The <picture> element can be particularly useful for two main purposes:

Bandwidth: For smaller screens or devices, there's no need to load large image files. By using the <picture> element and matching attributes, the browser can select the most suitable image and ignore any subsequent <source> tags.

Format Support: Some browsers or devices may not support certain image formats. The <picture> element enables you to add images of various formats, and the browser will use the first recognized format and ignore any following <source> tags.

Remember, the browser will only use the first <source> element that matches the attribute values, and will ignore any subsequent <source> elements.

Favicon

A favicon is a small image that appears next to the page title in the browser tab. Since it is small, it is recommended to use a simple image with high contrast.

To add a favicon to your website, you can either save the favicon image to the root directory of your web server or create a folder named "images" in the root directory and save the favicon image in it. A commonly used name for a favicon image is "favicon.ico".

<link rel="icon" type="image/x-icon" href="/images/favicon.ico">

Tables

Tables are a great way to display and organize data in HTML. In this tutorial, we'll cover the basics of creating tables in HTML and some common use cases.

Basic Table Structure

A basic HTML table consists of the following tags:

<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
  <tr>
    <td>Data 3</td>
    <td>Data 4</td>
  </tr>
</table>

The table tag defines the table element. The tr (table row) tag defines a row of cells in the table. The th (table header cell) tag defines a header cell in a table. By default, header cells are bold and centered. The td (table data cell) tag defines a standard cell in a table. Note that each tr tag contains one or more td or th tags.

Here's how the above code will look when rendered in the browser:

Header 1 Header 2
Data 1 Data 2
Data 3 Data 4

Table Attributes

Tables in HTML have a variety of attributes that can be used to control their appearance and behavior. Here are some of the most common:

  • border: Sets the width of the table borders. For example, border="1" would display a table with 1 pixel wide borders.
  • width: Sets the width of the table. You can specify this in pixels or as a percentage of the available space.
  • align: Sets the horizontal alignment of the table within its container. Possible values include left, center, and right.
  • cellpadding: Sets the amount of padding to be applied to the cells in the table. For example, cellpadding="5" would add 5 pixels of padding to each cell.
  • cellspacing: Sets the amount of space to be placed between cells in the table. For example, cellspacing="5" would create a 5-pixel gap between cells.

Here's an example of a table that uses some of these attributes:

<table border="1" width="50%" align="center" cellpadding="5" cellspacing="0">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
  <tr>
    <td>Data 3</td>
    <td>Data 4</td>
  </tr>
</table>

In browser:

Header 1 Header 2
Data 1 Data 2
Data 3 Data 4

To make cells as table header cells, use the HTML <th> tag instead of <td> tag. By default, the text within <th> tags are bold and centered, but you can modify this behavior by using CSS.

Table Borders

In HTML tables, you can add borders of various styles and shapes. When you add a border to a table, it also creates borders around each table cell. To add a border, use the CSS border property on the table, th, and td elements. To avoid having double borders, set the CSS border-collapse property to collapse. This will collapse the borders into a single border. To create an invisible border, set a background color for each cell and give the border a white color (same as the document background). You can also round the corners of the borders using the border-radius property. If you want to skip the border around the table, exclude the table from the CSS selector. You can set the appearance and color of the border using the border-style and border-color properties, respectively.

Table Sizes

HTML tables can have different sizes for each column, row, or the entire table. Use the style attribute with the width or height properties to specify the size of a table, row, or column. To set the width of a table, add the style attribute to the <table> element. When using a percentage as the size unit for a width, it means how wide the element will be compared to its parent element, which in this case is the <body> element. To set the size of a specific column, add the style attribute to a <th> or <td> element. To set the height of a specific row, add the style attribute to a table row element.

Table Headers

HTML tables can have headers for each column or row, or for many columns/rows. Table headers are defined with th elements, where each th element represents a table cell. To use the first column as table headers, define the first cell in each row as a <th> element. By default, table headers are bold and centered. To left-align the table headers, use the CSS text-align property. You can also have a header that spans over two or more columns using the colspan attribute on the <th> element. To add a caption to the entire table, use the <caption> tag, which should be inserted immediately after the <table> tag.

Table Padding and Spacing

HTML tables can adjust the padding inside the cells and the space between the cells. Cell padding is the space between the cell edges and the cell content. By default, the padding is set to 0. To add padding to table cells, use the CSS padding property. You can also add padding only above the content using the padding-top property and to the other sides using padding-bottom, padding-left, and padding-right properties. Cell spacing is the space between each cell, and by default, it is set to 2 pixels. To change the space between table cells, use the CSS border-spacing property on the table element.

Colspan and Rowspan

HTML tables can have cells that span over multiple rows and/or columns. To make a cell span over multiple columns, use the colspan attribute, where the value represents the number of columns to span. To make a cell span over multiple rows, use the rowspan attribute, where the value represents the number of rows to span.

Table Styling with Examples:

Zebra Stripes: One way to style tables is to add a background color to every other row to create a zebra stripes effect. This is achieved using the :nth-child(even) selector as follows:

Example:

tr:nth-child(even) {  
  background-color: #D6EEEE;
}

Note: Using :nth-child(odd) instead of (even) will result in styling occurring on row 1,3,5, etc. instead of row 2,4,6, etc.

Vertical Zebra Stripes: To create vertical zebra stripes, you can style every other column instead of every other row. This is achieved using the :nth-child(even) selector on table data elements as follows:

Example:

td:nth-child(even), th:nth-child(even) {
  background-color: #D6EEEE;
}

Note: If you want the styling to apply to both headers and regular table cells, use the :nth-child() selector on both th and td elements.

Combined Vertical and Horizontal Zebra Stripes: You can combine the above two examples to create stripes on every other row and every other column. Using a transparent color will result in an overlapping effect, but you can specify the transparency of the color using rgba().

Horizontal Dividers: To add horizontal dividers to a table, specify borders only at the bottom of each table row. This is achieved by adding the border-bottom property to all tr elements.

Example:

tr {
  border-bottom: 1px solid black;
}

Hoverable Table: Another way to style tables is to highlight table rows when the user hovers over them. This is achieved using the :hover selector on tr elements.

Example:

tr:hover {
  background-color: #D6EEEE;
}

HTML Table Colgroup: The <colgroup> element is used to style specific columns of a table. If you want to style the first two columns of a table, use the <colgroup> and <col> elements.

To specify the columns to be styled, use the <col> element within the <colgroup> element, which acts as a container for the column specifications. The span attribute specifies how many columns are affected by the style, and the style attribute specifies the style to be applied.

Note: The <colgroup> tag must be a child of a <table> element and should be placed before any other table elements, such as <thead>, <tr>, <td>, etc., but after the <caption> element, if present.

Legal CSS Properties: Only a limited selection of CSS properties are allowed to be used in the <colgroup> element:

  • width property
  • visibility property
  • background properties
  • border properties
  • All other CSS properties will have no effect on the table.

To style more columns with different styles, use additional <col> elements inside the <colgroup>.

If you want to style columns in the middle of a table, insert an "empty" <col> element (with no styles) for the columns before.

You can also hide columns using the visibility: collapse property.

Lists

HTML provides lists as a means for web developers to group a collection of related items.

Unordered List

An unordered list begins with the <ul> tag. Each list item starts with the <li> tag. By default, each list item will be marked with a small black circle.

The CSS list-style-type property can be used to define the style of the list item marker. It can have one of four values: disc, circle, square, none.

Lists can be nested, meaning that a list item (<li>) can contain a new list or other HTML elements, such as images and links.

CSS can be used to style HTML lists in many different ways, including horizontally to create navigation menus.

Ordered List

An ordered list begins with the <ol> tag. Each list item starts with the <li> tag. By default, each list item will be marked with a number.

The type attribute of the <ol> tag can be used to specify the type of the list item marker, including numbers, uppercase letters, lowercase letters, uppercase Roman numerals, and lowercase Roman numerals.

By default, an ordered list will start counting from 1. However, the start attribute can be used to begin counting from a specific number.

Description List

HTML also supports description lists, which consist of a list of terms with a description of each term.

A description list is defined using the <dl> tag, with each term defined using the <dt> tag and its corresponding description using the <dd> tag.

Block and Inline

Each HTML element comes with a default display value, which is determined by its type.

There are two primary display values: block and inline.

Block-Level Elements

A block-level element always starts on a new line, and the browser automatically adds some margin before and after the element. A block-level element occupies the entire available width (extending as far left and right as possible).

Two commonly used block-level elements are <p> and <div>. The <p> element indicates a paragraph in an HTML document. The <div> element denotes a division or section in an HTML document.

List:

<address><article><aside><blockquote><canvas><dd><div><dl><dt><fieldset><figcaption><figure><footer><form><h1>-<h6><header><hr><li><main><nav><noscript><ol><p><pre><section><table><tfoot><ul><video>

Inline Elements

An inline element does not begin on a new line. An inline element occupies only the necessary width. Note: An inline element cannot contain a block-level element!

List:

<a><abbr><acronym><b><bdo><big><br><button><cite><code><dfn><em><i><img><input><kbd><label><map><object><output><q><samp><script><select><small><span><strong><sub><sup><textarea><time><tt><var>

The <div> Element

The <div> element is frequently employed as a container for other HTML elements. Although the <div> element has no compulsory attributes, style, class, and id are frequently used. When combined with CSS, the <div> element can be used to style blocks of content.

The <span> Element

The <span> element is an inline container utilized to mark up a part of text or a part of a document. Although the <span> element has no compulsory attributes, style, class, and id are frequently used. When used together with CSS, the <span> element can be used to style sections of text.

Classes

The HTML class attribute is utilized to designate a class for an HTML element.

Multiple HTML elements can have the same class.

Using the Class Attribute

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

The class attribute can be utilized on any HTML element. The class name is sensitive to case!

Syntax for Class

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

Multiple Classes

HTML elements can belong to more than one class. To specify multiple classes, separate the class names with a space, such as <div class="one two">. The element will be styled according to all the specified classes.

Different HTML elements can reference the same class name. The class name can also be used by JavaScript to perform specific tasks for particular elements.

Id

The HTML id attribute is employed to designate a unique id for an HTML element. You cannot assign the same id to more than one element in an HTML document.

Using the id Attribute

The id attribute designates a unique id for an HTML element, and its value must be unique within the HTML document.

The id attribute is utilized to reference a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specified id.

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

The id name is sensitive to case! The id name must contain at least one character, cannot start with a number, and must not contain white spaces (spaces, tabs, etc.).

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

HTML bookmarks enable readers to navigate to specific parts of a webpage.

Bookmarks can be helpful if your page is lengthy.

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.

Using the id Attribute in JavaScript

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

Iframes

The <iframe> tag in HTML is utilized to specify an inline frame. The src attribute indicates the URL of the page to embed. It is recommended to always include a title attribute for screen readers. The height and width attributes are employed to specify the size of the iframe. To eliminate the border surrounding the iframe, utilize border:none; in the CSS styling. An <iframe> can serve as the target frame for a link in HTML.

To achieve this, the target attribute of the link should refer to the name attribute of the <iframe>.

JavaScript

JavaScript is utilized to create more dynamic and interactive HTML pages.

The <script> tag in HTML is used to define client-side scripts written in JavaScript.

This tag can either contain script statements or refer to an external script file using the src attribute.

Some common uses of JavaScript include image manipulation, form validation, and dynamic content changes.

To select an HTML element, JavaScript frequently employs the document.getElementById() method.

The <noscript> tag in HTML defines an alternative content that will be displayed to users who have either disabled scripts in their browser or are using a browser that does not support scripts.

File Paths

In web development, a file path is used to locate files within a website's folder structure. This includes files such as web pages, images, style sheets, and JavaScripts, among others.

There are two types of file paths: absolute and relative. An absolute file path describes the full path to a file on a server, starting from the root directory. A relative file path, on the other hand, points to a file relative to the current page. Using relative file paths is generally recommended, as it allows your web pages to be easily moved to different directories or servers without having to update all of your links.

Relative file paths are not bound to a specific base URL, which means that all links will work regardless of the domain or server. This is especially useful when developing websites locally on your own computer (localhost), as well as when transitioning to public domains.

HTML Head

The <head> element serves as a container for various types of metadata in HTML documents and is positioned between the <html> and <body> tags.

Metadata typically includes information about the document title, character set, styles, scripts, and other meta information, which is not displayed but utilized by browsers, search engines, and other web services.

The required <title> element defines the document's title, which appears in the browser's title bar or tab, and plays a vital role in search engine optimization (SEO). The <title> element should accurately and meaningfully describe the page's content.

The <style> element is used to define style information for a single HTML page, while the <link> element specifies the relationship between the current document and an external resource, such as an external style sheet.

The <meta> element typically specifies the character set, page description, keywords, author of the document, and viewport settings. It provides additional information for search engines and instructs browsers on how to display content or reload a page.

The <viewport> settings are crucial for mobile-friendly design and should include the following meta element in all web pages:

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

This element sets the width of the page to follow the device screen-width and defines the initial zoom level when the page is first loaded by the browser.

The <script> element defines client-side JavaScripts, and the <base> element specifies the base URL and/or target for all relative URLs in a page. It must have an href or a target attribute, or both, and there can only be one single <base> element in a document.

Tag Description
<head> Defines information about the document
<title> Defines the title of a document
<base> Defines a default address or a default target for all links on a page
<link> Defines the relationship between a document and an external resource
<meta> Defines metadata about an HTML document
<script> Defines a client-side script
<style> Defines style information for a document

HTML Layout

Web pages often display content in multiple columns, similar to how magazines or newspapers do.

HTML provides several semantic elements that define different parts of a web page:

HTML5 Semantic Elements

<header> - Defines a header for a document or a section <nav> - Defines a set of navigation links <section> - Defines a section in a document <article> - Defines independent, self-contained content <aside> - Defines content aside from the main content, like a sidebar <footer> - Defines a footer for a document or a section <details> - Defines additional details that the user can open and close on demand <summary> - Defines a heading for the <details> element


To create multicolumn layouts in HTML, there are four different techniques, each with its own advantages and disadvantages:

CSS Framework: You can use a pre-built CSS framework, like W3.CSS or Bootstrap, to quickly create your layout.

CSS Float Layout: This involves using the CSS float property to create the layout, which is easy to learn, but can harm the flexibility of the design.

CSS Flexbox Layout: This technique ensures that elements behave predictably when the page layout must accommodate different screen sizes and different display devices.

CSS Grid Layout: The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.

HTML Responsive

Responsive web design refers to the approach of designing web pages that can adjust their layout and content based on the screen size and device type being used to view them. It involves using HTML and CSS to automatically resize, hide, shrink, or enlarge elements on a webpage to ensure that it looks good on all devices, including desktops, tablets, and phones.

To achieve responsive design, you can add a viewport meta tag to your web pages, which gives the browser instructions on how to control the page's dimensions and scaling. Responsive images can be created using the CSS width or max-width property, and the <picture> element can be used to define different images for different browser window sizes. Additionally, text size can be set using a "vw" unit, which means the "viewport width."

Media queries are commonly used in responsive web design to define different styles for different browser sizes. All popular CSS frameworks offer responsive design and are free and easy to use.

Overall, the goal of responsive web design is to create a seamless and enjoyable user experience across all devices, regardless of screen size or device type.

HTML Computer code elements

HTML provides various elements for defining user input and computer code.

The <kbd> element is used to define keyboard input, and the content inside is displayed in the browser's default monospace font.

The <samp> element is used to define sample output from a computer program, and the content inside is displayed in the browser's default monospace font.

The <code> element is used to define a piece of computer code, and the content inside is displayed in the browser's default monospace font. However, note that the <code> element does not preserve extra whitespace and line-breaks. To preserve them, you can use the <pre> element to wrap the <code> element.

The <var> element is used to define a variable in programming or a mathematical expression, and the content inside is typically displayed in italic font.

Semantic Elements

Semantic elements in HTML are elements that convey a specific meaning to both the browser and the developer. They provide a clear structure and purpose to the content of the webpage.

Examples of non-semantic elements are <div> and <span>, which provide no information about their content.

On the other hand, semantic elements such as <form>, <table>, and <article> clearly define the content they contain.

HTML provides a range of semantic elements that can be used to structure different parts of a webpage, including:

<article> <aside> <details> <figcaption> <figure> <footer> <header> <main> <mark> <nav> <section> <summary> <time> HTML <section> Element

The <section> element is used to define a thematic grouping of content, usually with a heading. It can be used to separate different sections of a webpage, such as chapters, introduction, news items, or contact information.

HTML <article> Element

The <article> element is used to define independent and self-contained content, such as forum posts, blog posts, user comments, product cards, or newspaper articles. It should make sense on its own and be distributable independently from the rest of the webpage.

Nesting <article> in <section> or Vice Versa?

There are no strict rules on how to nest the <article> and <section> elements. Some HTML pages have <section> elements containing <article> elements, while others have <article> elements containing <section> elements.

HTML <header> Element

The <header> element is used to represent a container for introductory content or a set of navigational links. It typically contains one or more heading elements (<h1> - <h6>), a logo or icon, and authorship information. Multiple <header> elements can be used in one HTML document, but it cannot be placed within a <footer>, <address>, or another <header> element.

HTML <footer> Element

The <footer> element is used to define a footer for a document or section. It typically contains authorship information, copyright information, contact information, a sitemap, back-to-top links, and related documents. Multiple <footer> elements can be used in one document.

HTML <nav> Element

The <nav> element is used to define a set of navigation links. It is intended only for major blocks of navigation links, not for all links on a webpage. Browsers, such as screen readers for disabled users, can use this element to determine whether to omit the initial rendering of this content.

HTML <aside> Element

The <aside> element is used to define content aside from the content it is placed in, such as a sidebar. The content of the <aside> should be indirectly related to the surrounding content.

HTML <figure> and <figcaption> Elements

The <figure> element is used to specify self-contained content, such as illustrations, diagrams, photos, or code listings. The <figcaption> element is used to define a caption for a <figure> element and can be placed as the first or last child of the <figure> element. The <img> element defines the actual image or illustration.

HTML Style Guide

Consistent, clean HTML code makes it easy for others to understand. Guidelines for good HTML code:

Always declare the document type as <!DOCTYPE html> at the beginning. Use lowercase element and attribute names for cleaner code. Close all HTML elements, even if not required. Quote attribute values for readability, and use quotes if the value contains spaces. Specify alt, width, and height for images to ensure proper display and reduce flickering Avoid long code lines for easier readability Add blank lines and indentation for logical grouping and readability Never skip the <title> element as it is important for SEO and provides page titles in search results.

Omitting <html> and <body>? An HTML page will validate without the <html> and <body> tags. 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.

Close Empty HTML Elements? In HTML, it is optional to close empty elements.

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.

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:

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.

HTML Comments: Short comments should be written on one line. For longer comments, use the following format and indent with two spaces:

<!--
  Paragraph of text.
-->

Using Style Sheets: Use simple syntax for linking to style sheets, and avoid the unnecessary "type" attribute. Short CSS rules can be written compressed, while long CSS rules should be written over multiple lines with proper indentation and bracket placement.

Loading JavaScript in HTML: Use simple syntax for loading external scripts, and avoid the unnecessary "type" attribute.

Accessing HTML Elements with JavaScript: Using untidy HTML code can result in JavaScript errors.

File Names and Extensions: Use lowercase file names to avoid issues with case-sensitive servers. HTML files should have a .html extension, CSS files should have a .css extension, and JavaScript files should have a .js extension. There is no difference between the .htm and .html file extensions, and servers can be configured with multiple default filenames.

HTML Entities

Reserved characters in HTML should be replaced with character entities to avoid issues with the browser mixing them with tags. Character entities in HTML are used to display reserved characters, and can be represented by either an entity name or an entity number. Using an entity name is easy to remember, but browsers may not support all entity names. On the other hand, the support for entity numbers is good.

One commonly used entity in HTML is the non-breaking space ( ), which is a space that will not break into a new line. This is useful when breaking the words might be disruptive. Another common use of the non-breaking space is to prevent browsers from truncating spaces in HTML pages. The non-breaking hyphen (‑) is also used to define a hyphen character (‑) that does not break into a new line.


Character Entities

Result Description Entity Name Entity Number
non-breaking space    
< less than &lt; &#60;
> greater than &gt; &#62;
& ampersand &amp; &#38;
" double quotation mark &quot; &#34;
' single quotation mark (apostrophe) &apos; &#39;
¢ cent &cent; &#162;
£ pound &pound; &#163;
¥ yen &yen; &#165;
euro &euro; &#8364;
© copyright &copy; &#169;
® registered trademark &reg; &#174;

Diacritical marks, which are glyphs added to a letter, 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. Some diacritical marks, such as grave ( ̀ ) and acute ( ́ ), are called accents and can appear above and below a letter, inside a letter, or between two letters. It is important to note that entity names are case sensitive.


Diacritical marks

Mark Character Construct Result
̀ a a&#768;
́ a a&#769;
̂ a a&#770;
̃ a a&#771;
̀ O O&#768;
́ O O&#769;
̂ O O&#770;
̃ O O&#771;

HTML Symbols

In HTML, symbols that are not available on a standard keyboard can be added using entities.

Certain mathematical, technical, and currency symbols cannot be found on a regular keyboard.

To include these symbols in an HTML document, you may use either the entity name or number (represented in decimal or hexadecimal format) for the symbol.


Char Number Entity Description
&#8704; &forall; FOR ALL
&#8706; &part; PARTIAL DIFFERENTIAL
&#8707; &exist; THERE EXISTS
&#8709; &empty; EMPTY SETS
&#8711; &nabla; NABLA
&#8712; &isin; ELEMENT OF
&#8713; &notin; NOT AN ELEMENT OF
&#8715; &ni; CONTAINS AS MEMBER
&#8719; &prod; N-ARY PRODUCT
&#8721; &sum; N-ARY SUMMATION
Α &#913; &Alpha; GREEK CAPITAL LETTER ALPHA
Β &#914; &Beta; GREEK CAPITAL LETTER BETA
Γ &#915; &Gamma; GREEK CAPITAL LETTER GAMMA
Δ &#916; &Delta; GREEK CAPITAL LETTER DELTA
Ε &#917; &Epsilon; GREEK CAPITAL LETTER EPSILON
Ζ &#918; &Zeta; GREEK CAPITAL LETTER ZETA
© &#169; &copy; COPYRIGHT SIGN
® &#174; &reg; REGISTERED SIGN
&#8364; &euro; EURO SIGN
&#8482; &trade; TRADEMARK
&#8592; &larr; LEFTWARDS ARROW
&#8593; &uarr; UPWARDS ARROW
&#8594; &rarr; RIGHTWARDS ARROW
&#8595; &darr; DOWNWARDS ARROW
&#9824; &spades; BLACK SPADE SUIT
&#9827; &clubs; BLACK CLUB SUIT
&#9829; &hearts; BLACK HEART SUIT
&#9830; &diams; BLACK DIAMOND SUIT

HTML Emojis

Emojis are a set of characters from the UTF-8 character set: 😄 😍 💗

What are Emojis? Although emojis look like icons or images, they are actually letters (characters) that belong to the UTF-8 (Unicode) character set.

UTF-8 is designed to cover almost all of the characters and symbols used worldwide.

The HTML charset Attribute To ensure that a web browser displays an HTML page correctly, it must know the character set used in the page.

This is done by including the following <meta> tag:

If not specified, UTF-8 is the default character set in HTML. UTF-8 Characters Many UTF-8 characters cannot be typed on a keyboard, but they can be displayed using entity numbers (numbers that represent the characters):

A is 65 B is 66 C is 67

Emoji Characters Emojis are characters from the UTF-8 character set too:

😄 is 128516 😍 is 128525 💗 is 128151

Since Emojis are characters, they can be copied, displayed, and sized just like any other character in HTML.

HTML Charset

In order to properly display an HTML page, it is crucial for a web browser to know which character set to utilize.

From the inception of the internet, the first character encoding standard was ASCII. ASCII defined 128 different characters including numbers (0-9), English letters (A-Z), and some special characters like ! $ + - ( ) @ < >.

For HTML 4, ISO-8859-1 served as the default character set. This character set supported 256 different character codes. HTML 4 also supported UTF-8.

Originally used for Windows, ANSI (Windows-1252) is identical to ISO-8859-1 with the exception of having 32 extra characters.

With the HTML5 specification, web developers are encouraged to use the UTF-8 character set. UTF-8 covers nearly all of the characters and symbols in the world!

To specify the character set used in an HTML page, the <meta> tag is utilized with the following attribute:

<meta charset="UTF-8">

ASCII (American Standard Code for Information Interchange) was the first character encoding standard, initially developed in the 1960s to represent English characters on computers. It defines 128 different characters, including 33 non-printable control characters, and the printable characters consist of numbers (0-9), English letters (A-Z), and some special characters like ! $ + - ( ) @ < >. ASCII is a 7-bit encoding scheme, which means that it uses only seven bits of an 8-bit byte to represent each character.

ANSI (American National Standards Institute) is a US-based organization that defines standards for various industries, including computing. The ANSI character set, also known as Windows-1252 or CP1252, is a superset of the ISO-8859-1 character set. It includes all the characters from ISO-8859-1, plus an additional 32 characters, such as curly quotes, en dashes, and euro sign. ANSI is used as the default character set for many Windows applications.

ISO-8859-1 is a widely used 8-bit character encoding scheme that supports Western European languages, such as English, French, German, and Spanish. It includes characters from ASCII, plus 96 additional characters, including accented letters, punctuation marks, and symbols. ISO-8859-1 is often referred to as "Latin-1" and is commonly used in HTML documents.

UTF-8 (Unicode Transformation Format, 8-bit) is a character encoding scheme that supports all the characters and symbols in the Unicode standard, which covers almost all of the characters used in the world's languages. UTF-8 is a variable-width encoding scheme that uses between one and four bytes to represent each character, depending on its Unicode value. It is backward-compatible with ASCII, meaning that ASCII characters are represented using a single byte in UTF-8, while non-ASCII characters are represented using multiple bytes. UTF-8 is the recommended character encoding for web pages, as it can represent any character in the Unicode standard and is widely supported by modern web browsers.

HTML URL Encode (# Uniform Resource Locators)

HTML Uniform Resource Locators (URLs) are used to identify and locate resources on the internet, such as web pages, images, videos, and other types of files. A URL is composed of several parts, which together specify the location and type of the resource.

The basic structure of a URL is as follows:

protocol://domain-name-or-IP-address:port/path/filename

Let's take a closer look at each part of the URL:

Protocol: The protocol specifies the communication protocol to be used to access the resource. The most common protocols used in web browsing are HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP Secure).

Domain name or IP address: The domain name or IP address identifies the server where the resource is located. For example, in the URL "https://www.example.com/index.html", "www.example.com" is the domain name.

Port: The port number specifies the network port on the server where the resource is located. By default, HTTP uses port 80 and HTTPS uses port 443.

Path: The path specifies the location of the resource on the server's file system. It can be a directory path or a file path.

Filename: The filename specifies the name of the resource file.

Here's an example of a complete URL:

https://www.example.com:443/products/software/index.html

In this example, the protocol is HTTPS, the domain name is "www.example.com", the port is 443, the path is "/products/software/", and the filename is "index.html".

HTML URLs are used extensively in hyperlinks, which allow users to navigate from one web page to another by clicking on a link. URLs can also be typed directly into a web browser's address bar to access a specific resource on the internet.

HTML vs. XHTML

XHTML is a version of HTML that is more strict and XML-based. It was developed to make HTML more extensible and flexible, especially in working with other data formats such as XML. One of the main differences between XHTML and HTML is that XHTML documents must be "well-formed," meaning they must be marked up correctly. This is because XHTML is based on XML, which requires all documents to be well-formed.

To enforce the stricter markup requirements, XHTML has several key differences from HTML.

The Most Important Differences from HTML - Firstly, the <!DOCTYPE> declaration is mandatory. - The xmlns attribute in the <html> tag is also mandatory, as well as the <html>, <head>, <title>, and <body> tags. - Elements must always be properly nested, closed, and in lowercase, while attribute names and values must also be in lowercase and quoted. - Additionally, attribute minimization is not allowed in XHTML.

Despite these differences, XHTML is supported by all major web browsers.


HTML Forms

An HTML form is a section of a web page that allows users to input and submit data to a server for processing. It consists of various form elements such as input fields, checkboxes, radio buttons, dropdown lists, and buttons. When a user submits a form, the data is sent to a server using the HTTP POST or GET method.

Here are the main parts that make up an HTML form:

Form Element - The <form> tag is used to create an HTML form. It defines the start and end of a form.

Input Fields - The <input> tag is used to create various types of input fields, such as text fields, password fields, checkboxes, radio buttons, and more.


Type Description
<input type="text"> Displays a single-line text input field
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)
<input type="submit"> Displays a submit button (for submitting the form)
<input type="button"> Displays a clickable button

Labels - The <label> tag is used to create a label for an input field. This helps users understand what kind of information they should enter.

Select Lists - The <select> tag is used to create a dropdown list. It allows users to select one or more options from a list.

Text Areas - The <textarea> tag is used to create a multiline text input area.

Buttons - The <button> tag is used to create buttons that perform an action, such as submitting a form or resetting a form.

Hidden Fields - The <input type="hidden"> tag is used to create a field that is not visible to the user but contains data that is sent with the form when it is submitted.

Form Attributes

HTML form attributes are used to specify various properties and behaviors of HTML forms. Here are some of the most commonly used HTML form attributes:

action: Specifies the URL of the server-side script that will process the form data.

method: Specifies the HTTP method (either GET or POST) that the browser should use to submit the form data to the server.

enctype: Specifies the encoding type used to send the form data to the server. Common values are "application/x-www-form-urlencoded" (default) and "multipart/form-data" (used for file uploads).

name: Specifies a name for the form. This can be used by JavaScript to access the form element.

target: Specifies where to display the response received from the server after submitting the form. Common values are "_self" (default), "_blank", "_parent", and "_top".

autocomplete: Specifies whether the browser should enable autocomplete for form fields. Common values are "on" (default) and "off".

novalidate: Specifies that the browser should not validate the form data before submitting it to the server.

accept-charset: Specifies the character encoding used to submit the form data to the server. Common values are "UTF-8" (default) and "ISO-8859-1".

tabindex: Specifies the order in which form elements should be focused when the user presses the Tab key. The lower the number, the earlier the element is focused.

onsubmit: Specifies a JavaScript function to be executed when the form is submitted.

These are some of the most commonly used HTML form attributes, but there are many others that can be used to specify additional properties and behaviors.

Form Elements

HTML form elements are used to create a wide variety of form controls, such as text fields, checkboxes, radio buttons, drop-down lists, and buttons. Here are some of the most common form elements in HTML and a brief explanation of each:

<input>: This element is used to create a variety of form controls, such as text fields, checkboxes, radio buttons, buttons, and more. The type attribute of this element determines the type of control that will be created.

<label>: This element is used to associate a label with a form control, making it easier for users to understand what information is being requested.

<select>: This element is used to create a drop-down list, allowing users to select from a list of options.

<option>: This element is used to define the options within a drop-down list created by the <select> element.

<textarea> : This element is used to create a multi-line text input field, allowing users to enter larger amounts of text.

<button>: This element is used to create a clickable button that can trigger an action, such as submitting a form.

<fieldset>: This element is used to group related form controls together, making it easier to style and organize the form.

<legend>: This element is used to provide a caption for a <fieldset> element, helping to explain the purpose of the group of form controls.

<form>: This element is used to define a section of a web page that contains form controls, and specifies the action to be taken when the form is submitted. The method attribute of this element determines whether the form data will be sent using the HTTP GET or POST method.

Allow Multiple Selections:

Use the multiple attribute to allow the user to select more than one value. The multiple attribute works with the following input types: email, and file.

Input Types

The HTML <input> element supports different types, including:

<input type="button"> for a button that triggers a custom action. - checkbox - for selecting zero or more options from a limited set of choices. - color - for selecting a color, with a color picker appearing in the input field if supported by the browser. - date - for selecting a date, with a date picker appearing in the input field if supported by the browser. The min and max attributes can also be used to restrict the dates. - datetime-local - for specifying a date and time without a time zone, with a date picker appearing in the input field if supported by the browser. - email - for entering an email address, which can be automatically validated by some browsers. Smartphones may also recognize this type and provide a ".com" button on the keyboard. - file - for selecting a file to upload, with a "Browse" button provided by the browser. - hidden - for storing data that is not visible or modifiable by users, such as a database record ID. This type should not be used for security purposes. - image - for using an image as a submit button, with the path specified in the src attribute. - month - for selecting a month and year. - number - for entering a numeric value, with optional restrictions set by the min, max, and step attributes. - password - for entering a password, with the characters masked for privacy. - radio - for selecting one option from a limited set of choices. - range - for entering a numeric value within a range, with the default range being 0 to 100 and additional restrictions set by the min, max, and step attributes. - reset - for resetting the form data to its default values. - search - for entering search queries, behaving like a regular text field. - submit - for submitting the form data to a server page for processing, with the form-handler specified in the action attribute. The button's text can be customized by the value attribute. - tel - for entering a telephone number. - text - for entering a single-line text value. - time - for selecting a time without a time zone, with a time picker appearing in the input field if supported by the browser. - url - for entering a URL address, which can be automatically validated by some browsers. Smartphones may also provide a ".com" button on the keyboard. - week - for selecting a week and year, with a date picker appearing in the input field if supported by the browser.

Input restrictions:

  • checked - Specifies that an input field should be pre-selected when the page loads (for type="checkbox" or type="radio")
  • disabled - Specifies that an input field should be disabled
  • max - Specifies the maximum value for an input field
  • maxlength - Specifies the maximum number of character for an input field. When the "maxlength" attribute is set for an input field, it restricts the number of characters that can be entered to the specified limit. However, this attribute does not provide any visual or auditory feedback to the user. To notify the user of this limit, you would need to write JavaScript code.
  • min - Specifies the minimum value for an input field. The min and max attributes work with the following input types: number, range, date, datetime-local, month, time and week.
  • pattern - Specifies a regular expression to check the input value against. The pattern attribute works with the following input types: text, date, search, url, tel, email, and password.
  • readonly - Specifies that an input field is read only (cannot be changed)
  • required - Specifies that an input field is required (must be filled out). The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
  • size - Specifies the width (in characters) of an input field
  • step - Specifies the legal number intervals for an input field. For instance, if step="3", then legal input values might include -3, 0, 3, 6, and so on.Note that this attribute can be utilized with the "max" and "min" attributes to establish a range of acceptable values.The "step" attribute is compatible with the following input types: number, range, date, datetime-local, month, time, and week.
  • value - Specifies the default value for an input field

Others

  • placeholder- The "placeholder" attribute for an input field provides a brief suggestion that describes the anticipated value or format of the input (such as a sample value or a brief description). This suggestion is displayed within the input field before the user enters any text. The "placeholder" attribute is supported for the following input types: text, search, url, tel, email, and password.
  • autofocus - The input autofocus attribute specifies that an input field should automatically get focus when the page loads.
  • height and width - The height and width attributes specify the size of an <input type="image"> element, and it's important to always specify both attributes to reserve the space required for the image when the page loads. Otherwise, the page layout may change during loading.
  • list - The input list attribute refers to a <datalist> element that contains pre-defined options for an <input> element.
  • autocomplete - The input autocomplete attribute enables or disables autocomplete for a form or input field. Autocomplete predicts the value a user wants to enter based on previously typed values. This attribute is compatible with the <form> and various <input> types, including text, password, and datepickers.

Restricting input is not a fail-safe measure, as JavaScript offers several methods to bypass such restrictions. Therefore, it is necessary to verify the input on the receiving end (i.e. the server) to ensure safe and secure restriction.

Input Form Attributes

Form Attribute:

The form attribute in HTML specifies the form that the input element belongs to. The value of this attribute must be the same as the id attribute of the form element to which it belongs.

Formaction Attribute:

The formaction attribute of an input element specifies the URL of the file that will process the input when the form is submitted. This attribute overrides the action attribute of the form element. It can be used with the submit and image input types.

The formenctype Attribute

The formenctype attribute is used with the input element and specifies the encoding type of the form data when it is submitted. This attribute is only applicable for forms with the method attribute set to "post". It overrides the enctype attribute of the form element. The formenctype attribute can be used with the following input types: submit and image.

The formmethod Attribute

The input formmethod attribute specifies the HTTP method for submitting form-data to the action URL, and it overrides the method attribute of the form element. This attribute works with the input types submit and image, and the form-data can be sent as URL variables (method="get") or an HTTP post transaction (method="post").

When using the "get" method, the form-data is appended to the URL in name/value pairs, which is useful for form submissions where a user wants to bookmark the result. However, there is a limit to how much data can be placed in a URL, and sensitive information such as passwords should never be passed using this method as they will be visible in the browser's address bar.

In contrast, the "post" method sends the form-data as an HTTP post transaction, which cannot be bookmarked. This method is more secure and robust than "get" and does not have size limitations.

The formtarget Attribute

The formtarget attribute of an input element specifies a name or a keyword that indicates where to display the response that is received after submitting the form. This attribute overrides the target attribute of the form element. It works with the following input types: submit and image.

The formnovalidate Attribute

The formnovalidate attribute of an input element specifies that it should not be validated when submitted. This attribute overrides the novalidate attribute of the form element. It works with the following input types: submit.

The novalidate Attribute

The novalidate attribute is a form element attribute. When present, it specifies that all of the form-data should not be validated when submitted.


HTML Graphics

HTML Canvas

HTML5 canvas is an HTML element that is used to draw graphics and animations on a web page using JavaScript. The canvas is a rectangular area on an HTML page, where you can draw graphics, shapes, lines, text, and even add images. The graphics that are drawn on the canvas are rendered in real-time, which means that you can see the changes as they happen.

The canvas element has a height and width attribute, which determines the size of the canvas. The default size of the canvas is 300 pixels wide and 150 pixels high. You can set the size of the canvas using CSS or JavaScript.

To draw on the canvas, you need to use JavaScript. The canvas element provides a set of methods that you can use to draw shapes, lines, text, and images. You can also use gradients and patterns to create interesting effects.

The canvas element supports the following methods:

fillRect(x, y, width, height) strokeRect(x, y, width, height) clearRect(x, y, width, height) fillText(text, x, y) strokeText(text, x, y) beginPath() closePath() moveTo(x, y) lineTo(x, y) arc(x, y, radius, startAngle, endAngle, anticlockwise) quadraticCurveTo(cp1x, cp1y, x, y) bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) createLinearGradient(x0, y0, x1, y1) createRadialGradient(x0, y0, r0, x1, y1, r1) addColorStop(position, color)

You can also use the canvas element to create animations. Animations on the canvas are created by redrawing the canvas at regular intervals. You can use the requestAnimationFrame() method to create smooth animations.

In addition to drawing graphics and animations, the canvas element can also be used for image manipulation. You can load an image onto the canvas and then use JavaScript to manipulate the image.

Overall, the HTML5 canvas element provides a powerful way to create graphics, animations, and image effects on a web page.

HTML SVG

HTML5 SVG (Scalable Vector Graphics) is a markup language that allows the creation of 2D vector graphics. SVG is based on XML and is suitable for displaying on high-resolution screens. Unlike bitmap images, SVG graphics are scalable and can be zoomed or resized without losing image quality. SVG is widely used in web design, and it is supported by all modern web browsers.

SVG graphics are created using shapes, such as rectangles, circles, and polygons, as well as paths, which are defined using commands that specify lines, curves, and other shapes. SVG also supports gradients, patterns, and filters that can be applied to shapes to create a variety of visual effects.

SVG images can be created using a text editor or specialized graphic design software. The resulting SVG code can be embedded directly into an HTML document using the <svg> element, or it can be referenced using an external file. SVG graphics can be styled using CSS, and they can also be animated using JavaScript.

In summary, HTML5 SVG provides a powerful and flexible way to create scalable vector graphics that can be used in a wide variety of web design applications.


HTML Media

HTML Media is a powerful tool for presenting multimedia content on the web. HTML5 introduced several new elements, such as <audio>, <video>, and <source>, to allow for easier integration of media files into web pages.

The audio and video elements allow developers to embed audio and video content directly into a webpage without requiring any third-party plugins, making it easier to provide a seamless and consistent user experience across different devices and browsers.

The source element allows developers to specify multiple media files for a single audio or video element. This is useful when supporting different file types, such as MP3 and WAV for audio, or MP4 and WebM for video. The browser will choose the appropriate file based on the user's device and browser capabilities.

In addition to these elements, HTML also provides the <track> element, which allows developers to add subtitles, captions, and other forms of text-based content to media files.

Using the HTML5 media elements can greatly enhance the user experience of a website, but it's important to keep in mind that large media files can slow down page load times. It's also important to provide alternative content for users who cannot access or use the media content.

The multimedia elements like audio or video are stored in media files. To identify the type of a file, the most common method is to check its file extension. Multimedia files have different formats and extensions such as .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Formats

Video Formats

Format File Description
MPEG .mpg .mpeg MPEG. Developed by the Moving Pictures Expert Group. The first popular video format on the web. Not supported anymore in HTML.
AVI .avi AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
WMV .wmv WMV (Windows Media Video). Developed by Microsoft. Commonly used in video cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
QuickTime .mov QuickTime. Developed by Apple. Commonly used in video cameras and TV hardware. Plays well on Apple computers, but not in web browsers.
RealVideo .rm .ram RealVideo. Developed by Real Media to allow video streaming with low bandwidths. Does not play in web browsers.
Flash .swf .flv Flash. Developed by Macromedia. Often requires an extra component (plug-in) to play in web browsers.
Ogg .ogg Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML.
WebM .webm WebM. Developed by Mozilla, Opera, Adobe, and Google. Supported by HTML.
MPEG-4 or MP4 .mp4 MP4. Developed by the Moving Pictures Expert Group. Commonly used in video cameras and TV hardware. Supported by all browsers and  recommended by YouTube.

Only MP4, WebM, and Ogg video are supported by the HTML standard.

Audio formats

Format File Description
MIDI .mid .midi MIDI (Musical Instrument Digital Interface). Main format for all electronic music devices like synthesizers and PC sound cards. MIDI files do not contain sound, but digital notes that can be played by electronics. Plays well on all computers and music hardware, but not in web browsers.
RealAudio .rm .ram RealAudio. Developed by Real Media to allow streaming of audio with low bandwidths. Does not play in web browsers.
WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Plays well on Windows computers, but not in web browsers.
AAC .aac l AAC (Advanced Audio Coding). Developed by Apple as the default format for iTunes. Plays well on Apple computers, but not in web browsers.
WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows, Macintosh, and Linux operating systems. Supported by HTML.
Ogg .ogg Ogg. Developed by the Xiph.Org Foundation. Supported by HTML.
MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most popular format for music players. Combines good compression (small files) with high quality. Supported by all browsers.
MP4 .mp4 MP4 is a video format, but can also be used for audio. Supported by all browsers.

MP3 has established itself as the top choice for compressed recorded music, to the point that the term MP3 is often used interchangeably with digital music. Therefore, if your website deals with recorded music, it's recommended to use the MP3 format. Only MP3, WAV, and Ogg audio are supported by the HTML standard.

HTML Video

The HTML5 video element allows web developers to add video content to web pages without the need for plugins or third-party media players. This element supports multiple video formats such as MP4, WebM, and Ogg, and it also provides various attributes for customization, including controls, autoplay, loop, muted, and poster. Additionally, developers can use JavaScript to manipulate the video element, such as by adding event listeners and controlling playback.

The controls attribute enables video controls such as play, pause, and volume. It is recommended to set width and height attributes to prevent flickering while the video loads.

The source element specifies alternative video files to choose from. The first recognized format will be used by the browser.

Text between video and /video tags is displayed in non-supportive browsers.

HTML Audio

The HTML audio element is used to embed sound content in documents, and it comes with its own set of attributes. The controls attribute adds audio controls, like play, pause, and volume. It is recommended to always include width and height attributes. The source element allows you to specify alternative audio files which the browser may choose from. 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 add extra features to web browsers. They were initially developed for running Java applets, Microsoft ActiveX controls, displaying Flash movies, maps, scanning for viruses, and verifying a bank ID. However, most modern browsers have discontinued support for Java applets, ActiveX controls, and Shockwave Flash. The object element is supported by all browsers and is used to embed plug-ins (like Java applets, PDF readers, and Flash players) and HTML in web pages. The embed element is also supported in all major browsers and is used to embed an object within an HTML document, including HTML itself.

HTML YouTube

To play videos on a webpage using HTML, the simplest approach is to utilize YouTube. This is because the process of converting videos into various formats can be complex and consume a lot of time. Allowing YouTube to handle video playback on your site is a more straightforward alternative.

YouTube Video Id

Whenever a video is saved or played, YouTube generates an identification code (e.g., tgbNymZ7vqY). This code can be used to reference the video in the HTML code on your webpage.

Playing a YouTube Video in HTML

Upload the video to YouTube. Take note of the video identification code. Define an iframe element on your webpage. Set the "src" attribute to the video's URL. Use the "width" and "height" attributes to specify the player's dimensions. Add any other parameters you want to the URL.

YouTube Autoplay + Mute

Adding "autoplay=1" to the YouTube URL will allow your video to start playing automatically when a user visits the webpage. However, automatically starting a video can be frustrating for your visitors.

Most Chromium browsers do not permit autoplay in many cases. However, muted autoplay is always permitted.

To enable automatic video playback (but muted), add "mute=1" after "autoplay=1" to the YouTube URL.

YouTube Playlist:

You can play a sequence of videos (in addition to the original URL) by providing a comma-separated list of their identification codes.

YouTube Loop:

To enable a video to play repeatedly, add "loop=1" to the YouTube URL. A value of 0 (default) indicates that the video will play only once, whereas a value of 1 means that the video will loop indefinitely.

YouTube Controls:

To hide the player controls, add "controls=0" to the YouTube URL. A value of 0 implies that the controls will not display, while a value of 1 (default) implies that they will.


HTML APIs

HTML Geolocation API

The HTML Geolocation API is used to locate a user's position.

Locate the User's Position

The HTML Geolocation API allows you to obtain a user's geographic location. However, since this information could potentially compromise their privacy, it is not readily available unless they consent to it.

Beginning with Chrome 50, the Geolocation API only works in secure contexts, such as HTTPS. If your site is hosted on a non-secure origin (e.g., HTTP), requests to obtain the user's location will no longer function.

Using HTML Geolocation

The getCurrentPosition() method is used to return the user's position.

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

Example explained:

  • Check if Geolocation is supported
  • If supported, run the getCurrentPosition() method. If not, display a message to the user
  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
  • The showPosition() function outputs the Latitude and Longitude
  • The example above is a very basic Geolocation script, with no error handling.

Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}

Location-specific Information

Geolocation is particularly useful for providing location-specific information, such as:

  • Real-time local updates
  • Displaying points of interest near the user
  • Offering turn-by-turn navigation with GPS

The "getCurrentPosition()" method returns an object when it is successful. This object always includes the latitude, longitude, and accuracy properties.

The other properties are returned if available:

Property/ what Returns - coords.latitude The latitude as a decimal number (always returned) - coords.longitude The longitude as a decimal number (always returned) - coords.accuracy The accuracy of position (always returned) - coords.altitude The altitude in meters above the mean sea level (returned if available) - coords.altitudeAccuracy The altitude accuracy of position (returned if available) - coords.heading The heading as degrees clockwise from North (returned if available) - coords.speed The speed in meters per second (returned if available) - timestamp The date/time of the response (returned if available)

Geolocation Object - Other interesting Methods The Geolocation object also has other interesting methods:

  • watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
  • clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like smartphone):

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

HTML Drag/Drop API

In HTML, any element can be dragged and dropped. To make an element draggable, set the draggable attribute to true:

Example:

<!DOCTYPE html>
<html>
<head>
    <title>HTML Drag and Drop API Example</title>
    <style>
        #drag {
            width: 100px;
            height: 100px;
            background-color: orange;
            color: white;
            text-align: center;
            line-height: 100px;
        }
        #drop {
            width: 200px;
            height: 200px;
            background-color: lightblue;
            margin-top: 20px;
            padding: 10px;
        }
    </style>
    <script>
        function allowDrop(event) {
            event.preventDefault();
        }

        function drag(event) {
            event.dataTransfer.setData("text", event.target.id);
        }

        function drop(event) {
            event.preventDefault();
            var data = event.dataTransfer.getData("text");
            event.target.appendChild(document.getElementById(data));
        }
    </script>
</head>
<body>
    <div id="drag" draggable="true" ondragstart="drag(event)">Drag me!</div>
    <div id="drop" ondrop="drop(event)" ondragover="allowDrop(event)">Drop here!</div>
</body>
</html>

This code defines two elements: a draggable div element with id="drag" and a drop zone div element with id="drop". When the user drags the "Drag me!" box and drops it onto the "Drop here!" box, the contents of the "Drag me!" box are transferred to the "Drop here!" box.

Here are the steps involved in this example:

  • The allowDrop() function is called on the drop zone when a draggable element is dragged over it. This function prevents the default action of dropping the element by calling event.preventDefault().
  • The drag() function is called when the dragstart event is fired on the draggable element. This function sets the dataTransfer property of the event object to the id of the draggable element, which can be accessed later in the drop() function.
  • The drop() function is called when the drop event is fired on the drop zone. This function calls event.preventDefault() to prevent the default action of dropping the element, then retrieves the id of the draggable element from the dataTransfer property of the event object using event.dataTransfer.getData("text"). Finally, it appends the draggable element to the drop zone by calling event.target.appendChild(document.getElementById(data)).

HTML Web Storage API

HTML Web Storage, also known as Local Storage or DOM Storage, is a web browser feature that allows web applications to store data locally within the user's browser. It provides a way for websites to store key-value pairs in a user's web browser, allowing for persistent data storage that can be accessed even after the user closes their browser.

Web Storage comes in two types: sessionStorage and localStorage. sessionStorage stores data for a single session, meaning that the data will be lost when the user closes their browser or tab. On the other hand, localStorage stores data indefinitely, unless it is explicitly cleared by the user or the website.

Web Storage is implemented as part of the HTML5 specification and can be accessed using the Web Storage API, which provides methods for setting, getting, and removing data from the storage.

The Web Storage API is very easy to use and is supported by all modern web browsers, making it a popular choice for web developers looking to store data locally in the browser. It is commonly used for storing user preferences, shopping cart items, and other small amounts of data that need to be accessed across multiple pages or sessions.

HTML Web Storage Objects

HTML web storage provides two objects for storing data on the client:

  • window.localStorage - stores data with no expiration date
  • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

To use HTML Web Storage, you can access the localStorage and sessionStorage objects on the window object. Here's an example of how to set and get data using localStorage:

// Check if browser supports Web Storage
if (typeof(Storage) !== "undefined") {
  // Store data in localStorage
  localStorage.setItem("username", "john_doe");

  // Retrieve data from localStorage
  var username = localStorage.getItem("username");
  console.log("Username: " + username);
} else {
  // Sorry! No Web Storage support..
}
In the example above, we first check if the browser supports Web Storage using the typeof(Storage) check. If it does, we can use the localStorage object to store data using the setItem() method, and retrieve data using the getItem() method.

The data is stored as key-value pairs, where the key is a string and the value can be any type that can be serialized to a string, such as a number or object.

You can also remove a key-value pair using the removeItem() method or clear all data using the clear() method.

You can use the sessionStorage object in a similar way to store data for a single session.

The localStorage object is a type of HTML Web Storage that allows you to store key-value pairs on the client-side with no expiration date. This means that the data stored using localStorage will persist even after the user closes their browser, and will be available the next time they visit your website.

Here's an example of how to set and get data using localStorage:

// Store data in localStorage
localStorage.setItem("username", "john_doe");

// Retrieve data from localStorage
var username = localStorage.getItem("username");
console.log("Username: " + username);
In the example above, we store the string "john_doe" with the key "username" using the setItem() method. We then retrieve the value of "username" using the getItem() method and log it to the console.

You can also remove a key-value pair using the removeItem() method or clear all data using the clear() method.

It's important to note that localStorage is limited to around 5-10MB of storage space, depending on the browser. Exceeding this limit can cause the browser to prompt the user to clear their storage. Additionally, it's a good practice to handle cases where localStorage is not available, such as in older browsers or when the user has disabled it.

The sessionStorage object in HTML web storage is similar to the localStorage object, but it stores the data only for one session. When the user closes the browser tab, the data is automatically deleted, unlike the localStorage object where the data persists even after the browser is closed.

Here's a basic code example of using the sessionStorage object in JavaScript:

// Check if sessionStorage is supported by the browser
if (typeof(Storage) !== "undefined") {
  // Store data in sessionStorage
  sessionStorage.setItem("key", "value");

  // Retrieve data from sessionStorage
  var data = sessionStorage.getItem("key");

  // Remove data from sessionStorage
  sessionStorage.removeItem("key");

  // Clear all data from sessionStorage
  sessionStorage.clear();
} else {
  // Browser does not support sessionStorage
  console.log("Sorry, your browser does not support web storage...");
}

In the above example, we first check if the browser supports the sessionStorage object using the typeof(Storage) check. If supported, we can then use the setItem() method to store data in sessionStorage with a specified key-value pair. We can retrieve the stored data using the getItem() method, remove specific data using the removeItem() method, or clear all data using the clear() method. If the browser does not support web storage, an error message is logged to the console.

HTML Web Workers API

HTML Web Workers API is a feature of modern web browsers that allows web developers to execute scripts in the background thread of a web page. Web Workers are independent JavaScript scripts that run parallel to the main script, providing a way to perform computationally intensive tasks without blocking the UI or the main thread of the web page. This allows for a more responsive user experience as the page can still respond to user input while running long-running or resource-intensive scripts in the background.

The Web Worker API provides a way to run JavaScript code in the background without blocking the main thread. This is especially useful for heavy computations or operations that could potentially freeze the user interface.

Here's an example of using the Web Worker API to perform a simple computation in the background:

HTML File:

<!DOCTYPE html>
<html>
<head>
    <title>Web Worker Example</title>
</head>
<body>
    <h1>Web Worker Example</h1>
    <p>Result: <span id="result"></span></p>

    <script>
        // Create a new web worker
        const worker = new Worker("worker.js");

        // Listen for messages from the worker
        worker.onmessage = function(event) {
            document.getElementById("result").textContent = event.data;
        };

        // Send a message to the worker
        worker.postMessage(5);
    </script>
</body>
</html>

In this HTML file, we create a new Web Worker by calling the Worker constructor with the URL of the script file that contains the worker code. We then listen for messages from the worker using the onmessage event handler. When the worker sends a message back to the main thread, we update the content of the result span with the message data.

We also send a message to the worker using the postMessage method, passing in the value 5. This will be used by the worker to perform a computation and send the result back to the main thread.

Worker File:

// Listen for messages from the main thread
self.onmessage = function(event) {
    const result = fibonacci(event.data);
    // Send the result back to the main thread
    self.postMessage(result);
};

// Compute the nth Fibonacci number
function fibonacci(n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}
In this worker file, we listen for messages from the main thread using the onmessage event handler. When we receive a message, we call the fibonacci function with the message data and send the result back to the main thread using the postMessage method.

The fibonacci function is a recursive function that computes the nth Fibonacci number. We use this function to demonstrate a heavy computation that could potentially freeze the user interface if it were run in the main thread.

When we run this HTML file in a web browser, we should see the text "Result: 5" displayed on the page. This is the result of computing the 5th Fibonacci number in the worker and sending the result back to the main thread.

Web Workers and the DOM

Web Workers are a powerful feature of web browsers that allow developers to run JavaScript code in a separate thread from the main thread of the browser. This can be especially useful for performing long-running computations, downloading large files, or performing other CPU-intensive tasks that could otherwise block the user interface.

One important thing to note about Web Workers is that they are completely separate from the main thread, and therefore do not have access to the same JavaScript objects. In particular, Web Workers do not have access to the window, document, or parent objects, which are typically used to interact with the Document Object Model (DOM) of a web page.

This means that if you need to update the contents of a web page based on data computed in a Web Worker, you cannot directly access the DOM from within the worker. Instead, you must use messaging to communicate between the worker and the main thread.

When a Web Worker needs to update the DOM, it can send a message to the main thread with the necessary data. The main thread can then update the DOM using the usual JavaScript methods, such as getElementById or querySelector.

Similarly, if the main thread needs to pass data to a Web Worker for processing, it can send a message to the worker with the data. The worker can then perform the necessary computations and send the result back to the main thread using another message.

By using this messaging approach, Web Workers can still be used to perform complex computations or other CPU-intensive tasks, while still allowing the main thread to update the DOM and provide a responsive user interface.

HTML SSE API

HTML SSE (Server-Sent Events) is an API that allows a web page to receive real-time updates from a server over a single HTTP connection. This is in contrast to other real-time communication protocols like WebSockets, which require a separate TCP connection.

SSE works by establishing a long-lived HTTP connection between the client and the server. The server then sends periodic updates to the client over this connection using a specific format known as the "Server-Sent Event" format.

The SSE format consists of a series of text-based events, separated by newline characters. Each event can contain a set of key-value pairs, which are sent as plain text. An example of an SSE event might look like this:

event: update
data: {"name": "Alice", "age": 30}

In this example, the event has a name of "update", and the data payload is a JSON object containing two key-value pairs: "name" with a value of "Alice", and "age" with a value of 30.

To receive SSE updates in a web page, you can use the EventSource API. Here's an example:

const source = new EventSource('/sse');
source.addEventListener('update', function(event) {
  const data = JSON.parse(event.data);
  console.log(`Name: ${data.name}, Age: ${data.age}`);
});

In this example, we create a new EventSource object with the URL of the SSE endpoint ("/sse"). We then add an event listener for the "update" event, which will be triggered whenever an SSE event with the same name is received.

When the event is triggered, we parse the data payload as a JSON object and log it to the console.

One of the benefits of SSE is that it works over a standard HTTP connection, which means that it can be used with existing web servers and does not require any special network configuration. Additionally, SSE can be used with CORS (Cross-Origin Resource Sharing) to allow cross-domain communication between a web page and a server.


HTML References

HTML tag list HTML Attribute Reference HTML Global Attributes HTML Events HTML Colors HTML Canvas HTML Audio/Video HTML Doctypes HTML Character Sets HTML URL Encode HTML Lang Codes HTTP Messages HTTP Methods PX to EM Converter Keyboard Shortcuts

COMMENTS

Comments