and tags, along with their respective attributes like src, alt, width, and height. It also covers styling elements using the style attribute, text formatting elements, and how to use comments and color specifications in HTML. Key recommendations include using lowercase for attributes and quoting attribute values."> and tags, along with their respective attributes like src, alt, width, and height. It also covers styling elements using the style attribute, text formatting elements, and how to use comments and color specifications in HTML. Key recommendations include using lowercase for attributes and quoting attribute values.">
HTML Attruibut HTML Attruibut The source file (src), alternative text (alt), width, and height are provided as Example HTML Attributes Example Example Notes: External images might be under copyright. If you do not get permission 2. Relative URL - Links to an image that is hosted within the website. Here, the Tip: It is almost always best to use relative URLs. They will not break if you Example Example Example Example <!DOCTYPE html> Country codes can also be added to the language code in the lang attribute. So, The following example specifies English as the language and United States as <!DOCTYPE html> The value of the title attribute will be displayed as a tooltip when you mouse Example The title attribute (and all other attributes) can be written with uppercase or Bad: Sometimes you have to use quotes. This example will not display the title Example In some situations, when the attribute value itself contains double quotes, it is Or vice versa: Chapter Summary HTML Styles Example I am Big <tagname style="property:value;"> Background Color Example <body style="background-color:powderblue;"> <h1>This is a heading</h1> </body> Example <body> </body> Text Color Example Fonts Example Text Size Example Text Alignment Example Chapter Summary Example Example Example Tip: The <i> tag is often used to indicate a technical term, a phrase from Example The HTML <em> element defines emphasized text. The content inside is typically Tip: A screen reader will pronounce the words in <em> with an emphasis, using Example Example Example Example Example Example Notice that there is an exclamation point (!) in the start tag, but not in the end Note: Comments are not displayed by the browser, but they can help document Add Comments Example <p>This is a paragraph.</p> Hide Content Example You can also hide more than one line. Everything between the <!-- and the -- Example <p>This is a paragraph.</p> Comments are also great for debugging HTML, because you can comment out Example Color Names Tomato Orange DodgerBlue MediumSeaGreen Gray SlateBlue Violet Background Color Hello World Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy Example Text Color Hello World Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit Example Border Color Hello World Color Values The following three <div> elements have their background color set with RGB, #ff6347 Example This means that there are 256 x 256 x 256 = 16777216 possible colors! For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest To display white, set all color parameters to 255, like this: rgb(255, 255, 255). RED 255 GREEN 99 BLUE 71 Example rgb(255, 0, 0) rgb(0, 0, 255) Shades of Gray Example RED 255 GREEN 99 BLUE 71 ALPHA 0.5 Example #rrggbb For example, #ff0000 is displayed as red, because red is set to its highest value To display black, set all color parameters to 00, like this: #000000. To display white, set all color parameters to ff, like this: #ffffff. RED ff GREEN 63 BLUE 47 Example #ff0000 #0000ff #3cb371 #ee82ee #ffa500 Shades of Gray Example #404040 #686868 #a0a0a0 #bebebe #dcdcdc #f8f8f8 HSLA color values are an extension of HSL with an Alpha channel (opacity). HUE SATURATION 100% LIGHTNESS Example Saturation 50% is 50% gray, but you can still see the color. Lightness Example Shades of Gray Example HUE SATURATION 100% LIGHTNESS 50% ALPHA 0.5 Example CSS saves a lot of work. It can control the layout of multiple web pages all at What is CSS? With CSS, you can control the color, font, the size of text, the spacing between Tip: The word cascading means that a style applied to a parent element will Using CSS The most common way to add CSS, is to keep the styles in external CSS files. Inline CSS The following example sets the text color of the <h1> element to blue, and the Example Internal CSS The following example sets the text color of ALL the <h1> elements (on that Example <h1>This is a heading</h1> </body> External CSS To use an external style sheet, add a link to it in the <head> section of each HTML Example <h1>This is a heading</h1> </body> The external style sheet can be written in any text editor. The file must not "styles.css": Tip: With an external style sheet, you can change the look of an entire web site, Example <!DOCTYPE html> <h1>This is a heading</h1> </body> CSS Border Tip: You can define a border for nearly all HTML elements. Example p { CSS Padding Example p { Example p { Example Example Example For a complete list of all available HTML tags, HTML Tag Reference. When you move the mouse over a link, the mouse arrow will turn into a little Note: A link does not have to be text. A link can be an image or any other HTML The most important attribute of the <a> element is the href attribute, which The link text is the part that will be visible to the reader. Clicking on the link text, will send the reader to the specified URL address. Example Tip: Links can of course be styled with CSS, to get another look! Example A local link (a link to a page within the same website) is specified with Example <h2>Relative URLs</h2> Example Example Button as a Link Example Link Titles Example Example Example Chapter Summary For a complete list of all available HTML tags, HTML Tag Reference. Example <style> a:visited { a:hover { a:active { Link Buttons This is a link Example a:hover, a:active { To create a bookmark - first create the bookmark, then add a link to it. When the link is clicked, the page will scroll down or up to the location with the Example Then, add a link to the bookmark ("Jump to Chapter 4"), from within the same Example Chapter Summary HTML Images Images can improve the design and the appearance of a web page. Example Example Example Images are not technically inserted into a web page; images are linked to web The <img> tag is empty, it contains attributes only, and does not have a closing Syntax Note: When a web page loads, it is the browser, at that moment, that gets the Example Example If a browser cannot find an image, it will display the value of the alt attribute: Example Tip: A screen reader is a software program that reads the HTML code, and Example Example The width and height attributes always define the width and height of the image However, we suggest using the style attribute. It prevents styles sheets from Example </body> Example To point to an image on another server, you must specify an absolute (full) URL Example Animated Images Example Image as a Link Example Image Floating Example Chapter Summary Note: Loading large images takes time, and can slow down your web page. Use Image Maps Try to click on the computer, phone, or the cup of coffee in the image below: <map name="workmap"> The Image The usemap value starts with a hash tag # followed by the name of the image The <map> element is used to create an image map, and is linked to the image <map name="workmap"> The name attribute must have the same value as the <img>'s usemap attribute . The Areas You must also define some coordinates to be able to place the clickable area Shape="rect" So, the coordinates 34,44 is located 34 pixels from the left margin and 44 pixels Example This is the area that becomes clickable and will send the user to the page 337,300 44 pixels Example This is the area that becomes clickable and will send the user to the page Shape="poly" How can we make the croissant in the image below become a clickable link? Example Example <map name="workmap"> <script> Chapter Summary Example You can also specify the background image in the <style> element, in Example Example <style> Background Repeat Example To avoid the background image from repeating itself, set the background- Example Background Cover Also, to make sure the entire element is always covered, set the background- This way, the background image will cover the entire element, with no Example Background Stretch Try resizing the browser window, and you will see that the image will stretch, Example Each <source> element has a media attribute that defines when the image is Example <picture> 1. Bandwidth 2. Format Support Example <picture> Note: The browser will use the first <source> element with matching attribute HTML Favicon A favicon image is displayed to the left of the page title in the browser tab, like To add a favicon to your website, either save your favicon image to the root Next, add a <link> element to your "index.html" file, after the <title> element, Example <h1>This is a Heading</h1> </body> Now, save the "index.html" file and reload it in your browser. Your browser tab Example </body> The title should describe the content and the meaning of the page. HTML Tables Example Example <table> Table Cells Everything between <td> and </td> are the content of the table cell. Example Note: A table cell can contain all sorts of HTML elements: text, images, lists, Table Rows Example You can have as many rows as you like in a table; just make sure that the Note: There are times when a row can have less or more cells than another. Table Headers Example <table> By default, the text in <th> elements are bold and centered, but you can change Example Example Skip the border around the table by leaving out table from the css selector: Example dotted outset Example Border Color Example Use the style attribute with the width or height properties to specify the Example <table style="width:100%"> Note: Using a percentage as the size unit for a width means how wide will this Example <table style="width:100%"> To set the height of a specific row, add the style attribute on a table row Example <table style="width:100%"> TOBIAS LINUS 8:00 9:00 10:00 11:00 12:00 13:00 8:00 9:00 10:00 11:00 12:00 DECEMBER Example Example Jill Smith 50 Eve Jackson 94 Example Jill Smith 50 Eve Jackson 94 Example You will learn more about colspan and rowspan in the Table colspan & Table Caption Monthly savings Month Savings January $100 Example With Padding With Spacing Example To add padding only above the content, use the padding-top property. And the others sides with the padding-bottom, padding-left, and padding- Example To change the space between table cells, use the CSS border- Example NAME APRIL 2022 Example Note: The value of the colspan attribute represents the number of columns to Example Note: The value of the rowspan attribute represents the number of rows to 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 To style every other table row element, use the :nth-child(even) selector like Example Note: If you use (odd) instead of (even), the styling will occur on row 1,3,5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Example Note: Put the :nth-child() selector on both th and td elements if you want Example th:nth-child(even),td:nth-child(even) { Horizontal Dividers If you specify borders only at the bottom of each table row, you will have a table Example Hoverable Table Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 The span attribute specifies how many columns that get the style. Example Note: The <colgroup> tag must be a child of a <table> element and should be width property Empty Colgroups Example Hide Columns Example Example Item 1. First item The list items will be marked with bullets (small black circles) by default: Example Example The <dl> tag defines the description list, the <dt> tag defines the term (name), Example The list items will be marked with bullets (small black circles) by default: Example Value Description Example - Disc Example - Circle Example - Square Example - None Example Note: A list item (<li>) can contain a new list, and other HTML elements, like Example li a { li a:hover { <ul> </body> Chapter Summary Type Description Uppercase Letters: Lowercase Letters: Example Example Note: A list item (<li>) can contain a new list, and other HTML elements, like Chapter Summary The <dl> tag defines the description list, the <dt> tag defines the term (name), Example Chapter Summary The two most common display values are block and inline. Block-level Elements A block-level element always takes up the full width available (stretches out to Example <address> <article> <aside> <canvas> <dd> <div> <dl> <dt> <fieldset> <figcaption> <figure> <footer> <form> <h1>-<h6> <header> <hr> <li> <main> <nav> <noscript> <ol> <p> <pre> <section> <table> <tfoot> <video> Inline Elements Example Try it Yourself » <a> <abbr> <acronym> <b> <bdo> <big> <br> <button> <cite> <code> <dfn> <i> <img> <input> <kbd> <label> <map> <object> <output> <q> <samp> <script> <select> <small> <span> <strong> <sub> <sup> <textarea> <time> <tt> <var> The <div> element has no required attributes, but style, class and id are When used together with CSS, the <div> element can be used to style blocks of Example You will learn more about the <div> element in the next chapter. The <span> element has no required attributes, but style, class and id are When used together with CSS, the <span> element can be used to style parts of Example HTML Tags London Oslo Rome There are different methods for aligning elements side by side, all include some Float The CSS float property is used for positioning and formatting content and allow Example <style> Result Oslo Rome Inline-block Example Result Oslo Rome Flex To make the CSS flex method work, surround the <div> elements with Example Result Oslo Rome Grid Sounds almost the same as flex, but has the ability to define more than one row The CSS grid method requires that you surround the <div> elements with <style> Result Oslo Rome HTML Tags In the following example, both <h2> and <p> point to the "city" class and will Example Example <script> Try it Yourself » Don't worry if you don't understand the code in the example above. You will learn more about JavaScript in our HTML JavaScript chapter, or you can Chapter Summary HTML id Attribute You cannot have more than one element with the same id in an HTML The syntax for id is: write a hash character (#), followed by an id name. Then, In the following example we have an <h1> element that points to the id name Example </body> Note: The id name must contain at least one character, cannot start with a <h2 class="city">Paris</h2> <h2 class="city">Tokyo</h2> Then, when the link is clicked, the page will scroll to the location with the Example Then, add a link to the bookmark ("Jump to Chapter 4"), from within the same Example Or, add a link to the bookmark ("Jump to Chapter 4"), from another page: Example <script> HTML Iframes An inline frame is used to embed another document within the current HTML Syntax Tip: It is a good practice to always include a title attribute for the <iframe>. Example Example To remove the border, add the style attribute and use the Example With CSS, you can also change the size, style and color of the iframe's border: Example The target attribute of the link must refer to the name attribute of the iframe: Chapter Summary Example Common uses for JavaScript are image manipulation, form validation, and This JavaScript example writes "Hello JavaScript!" into an HTML element with A Taste of JavaScript Example Example document.getElementById("demo").style.fontSize = "25px"; Example document.getElementById("image").src = "picture.gif"; Example Web pages Example In the following example, the file path points to a file in the images folder Example In the following example, the file path points to a file in the images folder Example Example Best Practice When using relative file paths, your web pages will not be bound to your current HTML metadata is data about the HTML document. Metadata is not displayed. Metadata typically define the document title, character set, styles, scripts, and The content of a page title is very important for search engine optimization Example </body> Example The <link> tag is most often used to link to external style sheets: Example The metadata will not be displayed on the page, but is used by browsers (how to Examples <meta charset="UTF-8"> Setting the viewport to make your website look good on all devices: Example You should include the following <meta> element in all your web pages: This gives the browser instructions on how to control the page's dimensions and The width=device-width part sets the width of the page to follow the screen- The initial-scale=1.0 part sets the initial zoom level when the page is first Here is an example of a web page without the viewport meta tag, and the same The following JavaScript writes "Hello JavaScript!" into an HTML element with Example The <base> tag must have either an href or a target attribute present, or both. Example <head> <body> Chapter Summary Cities London Standing on the River Thames, London has been a major settlement for two millennia, its Footer CSS framework CSS Frameworks Example Cities London Standing on the River Thames, London has been a major settlement for two millennia, its Footer Example Cities London Standing on the River Thames, London has been a major settlement for two millennia, its Footer A responsive web design will automatically adjust for different screen sizes Example This will set the viewport of your page, which will give the browser instructions Here is an example of a web page without the viewport meta tag, and the same Tip: If you are browsing this page on a phone or a tablet, you can click on the Responsive Images Notice that in the example above, the image can be scaled up to be larger than Example That way the text size will follow the size of the browser window: Hello World Example With media queries you can define completely different styles for different Example: resize the browser window to see that the three div elements below Left Menu Main Content Right Content Example .main { London It is the most populous city in the United Kingdom, with a metropolitan area of Paris The Paris area is one of the largest population centers in Europe, with more than Tokyo It is the center of the Greater Tokyo Area, and the most populous metropolitan Example <div class="w3-row-padding"> <div class="w3-third"> <div class="w3-third"> </body> Example Examples of non-semantic elements: <div> and <span> - Tells nothing about its In HTML there are some semantic elements that can be used to define different <article> Chapters A web page could normally be split into sections for introduction, content, and Example <section> An article should make sense on its own, and it should be possible to distribute Forum posts Example <article> <article> <article> Example 2 <html> .browser { <article class="all-browsers"> </body> Can we use the definitions to decide how to nest those elements? No, we Example <article> authorship information Example <footer> Notice that NOT all links of a document should be inside a <nav> element. Browsers, such as screen readers for disabled users, can use this element to Example <nav> Example <p>My family and I visited The Epcot center this summer. The <aside> Example 2 <html> <p>My family and I visited The Epcot center this summer. The <aside> <p>My family and I visited The Epcot center this summer. The </body> Example Tag Description HTML Symbols To add such symbols to an HTML page, you can use the entity name or the Example Emoji Value 🗻 🗻 🗼 🗼 🗽 🗽 🗾 🗾 🗿 🗿 😀 😀 😂 😂 😃 😃 😄 😄 😅 😅 💺💻💼💽💾 👮👯👰👱👲 🐂🐃🐄🐅🐆 They are letters (characters) from the UTF-8 (Unicode) character set. UTF-8 covers almost all of the characters and symbols in the world. <meta charset="UTF-8"> UTF-8 Characters A is 65 Example </body> Example Explained The characters A, B, and C, are displayed by the numbers 65, 66, and 67. To let the browser understand that you are displaying a character, you must Emoji Characters 😄 is 128516 Example <p>😀</p> </body> Since Emojis are characters, they can be copied, displayed, and sized just like Example <h1>Sized Emojis</h1> <p style="font-size:48px"> </body> Example Last name: Submit <form> The <form> element is a container for different types of input elements, such as: All the different form elements are covered in this chapter: HTML Form Type Description All the different input types are covered in this chapter: HTML Input Types. Text Fields <form> First name: Last name: Note: The form itself is not visible. Also note that the default width of an input The <label> element is useful for screen-reader users, because the screen- The <label> element also helps users who have difficulty clicking on very small The for attribute of the <label> tag should be equal to the id attribute of Radio Buttons Example <form> HTML Checkboxes Example I have a bike The form-handler is typically a file on the server with a script for processing Example <form action="/action_page.php"> Last name: Submit If the name attribute is omitted, the value of the input field will not be sent at all. Example <form action="/action_page.php"> Usually, the form data is sent to a file on the server when the user clicks on the Example <form action="/action_page.php"> Tip: If the action attribute is omitted, the action is set to the current page. Value Description The default value is _self which means that the response will open in the Example Example Example Notes on GET: Notes on POST: Appends the form data inside the body of the HTTP request (the Tip: Always use POST if the form data contains sensitive or personal Example When present, it specifies that the form-data (input) should not be validated enctype Specifies how the form-data should be encoded when submitting it to the novalidate Specifies that the form should not be validated when submitted target Specifies where to display the response that is received after submitting The graphic to the left is created with <canvas>. It shows four elements: a Canvas Examples Example Add a JavaScript Draw a Line Example Draw a Circle Example Draw a Text Example Example Example // Create gradient Example // Create gradient Draw Image SVG graphics are scalable, and do not lose any quality if they are zoomed or SVG What is SVG? SVG has several methods for drawing paths, rectangles, circles, polygons, text, SVG Circle </body> SVG Rectangle SVG Star Example SVG is XML based, which means that every element is available within the SVG SVG Canvas HTML Multimedia What is Multimedia? Web pages often contain multimedia elements of different types and formats. Browser Support Multimedia Formats The most common way to discover the type of a file, is to look at the file MPEG .mpg MPEG. Developed by the Moving Pictures Expert Group. The Note: Only MP4, WebM, and Ogg video are supported by the HTML standard. MIDI .mid MIDI (Musical Instrument Digital Interface). Main format for all WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Plays well WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows, MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the MP4 .mp4 MP4 is a video format, but can also be used for audio. Supported Note: Only MP3, WAV, and Ogg audio are supported by the HTML standard. HTML Video Example Example It is a good idea to always include width and height attributes. If height and The <source> element allows you to specify alternative video files which the The text between the <video> and </video> tags will only be displayed in Example Add muted after autoplay to let your video start playing automatically (but Example Element MP4 video/mp4 WebM video/webm Ogg video/ogg This allows you to load, play, and pause videos, as well as setting duration and There are also DOM events that can notify you when a video begins to play, is HTML Audio Example The <source> element allows you to specify alternative audio files which the The text between the <audio> and </audio> tags will only be displayed in Example Add muted after autoplay to let your audio file start playing automatically (but Example Browser Support Element *From Edge 79 MP3 audio/mpeg OGG audio/ogg WAV audio/wav This allows you to load, play, and pause audios, as well as set duration and HTML Plug-ins Plug-ins Warning ! The support for Shockwave Flash has also been turned off in modern browsers. It was designed to embed plug-ins (like Java applets, PDF readers, and Flash Example Example Web browsers have supported the <embed> element for a long time. However, Example Example An easier solution is to let YouTube play the videos in your web page. YouTube Video Id You can use this id, and refer to your video in the HTML code. Example Add mute=1 after autoplay=1 to let your video start playing automatically (but YouTube Playlist YouTube Loop YouTube - Loop YouTube Controls YouTube - Controls Since this can compromise privacy, the position is not available unless the user Try It Browser Support API Note: As of Chrome 50, the Geolocation API will only work on secure contexts The example below returns the latitude and longitude of the user's position: Example function getLocation() { function showPosition(position) { Example explained: The example above is a very basic Geolocation script, with no error handling. Example Property Returns coords.altitude The altitude in meters above the mean sea level (returned The example below shows the watchPosition() method. You need an accurate Example function getLocation() { Example Browser Support API Example function drag(ev) { function drop(ev) { </body> It might seem complicated, but lets go through all the different parts of a drag <img draggable="true"> The dataTransfer.setData() method sets the data type and the value of the function drag(ev) { In this case, the data type is "text" and the value is the id of the draggable event.preventDefault() function drop(ev) { Code explained: Web storage is per origin (per domain and protocol). All pages, from one origin, Browser Support API Before using web storage, check browser support for localStorage and Example // Retrieve Example explained: // Store localStorage.removeItem("lastname"); The following example counts the number of times a user has clicked a button. Example The following example counts the number of times a user has clicked a button, Example Browser Support API Example var i = 0; function timedCount() { timedCount(); The important part of the code above is the postMessage() method - which is Note: Normally web workers are not used for such simple scripts, but for more The following lines checks if the worker already exists, if not - it creates a new if (typeof(w) == "undefined") { w.onmessage = function(event){ When the web worker posts a message, the code within the event listener is w.terminate(); w = undefined; Example <script> function startWorker() { function stopWorker() { </body> This was also possible before, but the web page would have to ask if any Browser Support API Example explained: Create a new EventSource object, and specify the URL of the page The server-side event stream syntax is simple. Set the "Content-Type" header to $time = date('r'); <% Code explained: Events DescriptionUploaded by
ashusinghbaghel45Uploaded by
ashusinghbaghel45HTML Images
HTML images are defined with the <img> tag.
attributes:
<img src="instagram.jpg" alt="instagram.com" width="104" height="14
2">
All HTML elements can have attributes
Attributes provide additional information about elements
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"The href Attribute
The <a> tag defines a hyperlink. The href attribute specifies the URL of the page
the link goes to:
<a href="https://www.instagram.com">Visit Schools</a>The src Attribute
The <img> tag is used to embed an image in an HTML page. The src attribute
specifies the path to the image to be displayed:
<img src="img_girl.jpg">
There are two ways to specify the URL in the src attribute:1. Absolute URL - Links to an external image that is hosted on another
website. Example: src="https://www.w3schools.com/images/img_girl.jpg".
to use it, you may be in violation of copyright laws. In addition, you cannot
control external images; it can suddenly be removed or changed.
URL does not include the domain name. If the URL begins without a slash, it will
be relative to the current page. Example: src="img_girl.jpg". If the URL begins
with a slash, it will be relative to the domain. Example:
src="/images/img_girl.jpg".
change domain.The width and height Attributes
The <img> tag should also contain the width and height attributes, which specify
the width and height of the image (in pixels):
<img src="img_girl.jpg" width="500" height="600">The alt Attribute
The required alt attribute for the <img> tag specifies an alternate text for an
image, if the image for some reason cannot be displayed. This can be due to a
slow connection, or an error in the src attribute, or if the user uses a screen
reader.
<img src="img_girl.jpg" alt="Girl with a jacket">
See what happens if we try to display an image that does not exist:<img src="img_typo.jpg" alt="Girl with a jacket">
The style Attribute
The style attribute is used to add styles to an element, such as color, font, size,
and more.
<p style="color:red;">This is a red paragraph.</p>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.The following example specifies English as the language:
<html lang="en">
<body>
...
</body>
</html>
the first two characters define the language of the HTML page, and the last two
characters define the country.
the country:
<html lang="en-US">
<body>
...
</body>
</html>The title Attribute
The title attribute defines some extra information about an element.
over the element:
<p title="I'm a tooltip">This is a paragraph.</p>We Suggest: Always Use Lowercase
Attributes
The HTML standard does not require lowercase attribute names.
lowercase like title or TITLE.However, W3C recommends lowercase attributes in HTML,
and demands lowercase attributes for stricter document types like XHTML.At we always use lowercase attribute names.
We Suggest: Always Quote Attribute
Values
The HTML standard does not require quotes around attribute values.However, recommends quotes in HTML, and demands quotes for stricter
document types like XHTML.
Good:
<a href="https://www.instagram.com/html/">Visit our HTML
tutorial</a>
<a href=https://www.instagram.com/html/>Visit our HTML tutorial</a>
attribute correctly, because it contains a space:
<p title=About W3Schools>we always use quotes around attribute values.
Single or Double Quotes?
Double quotes around attribute values are the most common in HTML, but single
quotes can also be used.
necessary to use single quotes:<p title='John "ShotGun" Nelson'>
<p title="John 'ShotGun' Nelson">
All HTML elements can have attributes
The href attribute of <a> specifies the URL of the page the link goes to
The src attribute of <img> specifies the path to the image to be displayed
The width and height attributes of <img> provide size information for
images
The alt attribute of <img> provides an alternate text for an image
The style attribute is used to add styles to an element, such as color,
font, size, and more
The lang attribute of the <html> tag declares the language of the Web
page
The title attribute defines some extra information about an element
The HTML style attribute is used to add styles to an element, such as color,
font, size, and more.
I am Red
I am BlueThe HTML Style Attribute
Setting the style of an HTML element, can be done with the style attribute.The HTML style attribute has the following syntax:
The property is a CSS property. The value is a CSS value.
The CSS background-color property defines the background color for an HTML
element.
Set the background color for a page to powderblue:
<p>This is a paragraph.</p>
Set background color for two different elements:<h1 style="background-color:powderblue;">This is a heading</h1>
<p style="background-color:tomato;">This is a paragraph.</p>
The CSS color property defines the text color for an HTML element:
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
The CSS font-family property defines the font to be used for an HTML
element:
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
The CSS font-size property defines the text size for an HTML element:
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
The CSS text-align property defines the horizontal text alignment for an HTML
element:
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
Use the style attribute for styling HTML elements
Use background-color for background color
Use color for text colors
Use font-family for text fonts
Use font-size for text sizes
Use text-align for text alignment
HTML Text Formatting
HTML contains several elements for defining text with a special meaning.
This text is boldThis text is italic
This is subscript and superscript
HTML Formatting Elements
Formatting elements were designed to display special types of text: <b> - Bold text
<strong> - Important text
<i> - Italic text
<em> - Emphasized text
<mark> - Marked text
<small> - Smaller text
<del> - Deleted text
<ins> - Inserted text
<sub> - Subscript text
<sup> - Superscript textHTML <b> and <strong> Elements
The HTML <b> element defines bold text, without any extra importance.
<b>This text is bold</b>
The HTML <strong> element defines text with strong importance. The content
inside is typically displayed in bold.
<strong>This text is important!</strong>HTML <i> and <em> Elements
The HTML <i> element defines a part of text in an alternate voice or mood. The
content inside is typically displayed in italic.
another language, a thought, a ship name, etc.
<i>This text is italic</i>
displayed in italic.
verbal stress.
<em>This text is emphasized</em>HTML <small> Element
The HTML <small> element defines smaller text:
<small>This is some smaller text.</small>
HTML <mark> Element
The HTML <mark> element defines text that should be marked or highlighted:
<p>Do not forget to buy <mark>milk</mark> today.</p>HTML <del> Element
The HTML <del> element defines text that has been deleted from a document.
Browsers will usually strike a line through deleted text:
<p>My favorite color is <del>blue</del> red.</p>HTML <ins> Element
The HTML <ins> element defines a text that has been inserted into a document.
Browsers will usually underline inserted text:
<p>My favorite color is <del>blue</del> <ins>red</ins>.</p>HTML <sub> Element
The HTML <sub> element defines subscript text. Subscript text appears half a
character below the normal line, and is sometimes rendered in a smaller font.
Subscript text can be used for chemical formulas, like H 2O:
Example
<p>This is <sub>subscripted</sub> text.</p>HTML <sup> Element
The HTML <sup> element defines superscript text. Superscript text appears half a
character above the normal line, and is sometimes rendered in a smaller font.
Superscript text can be used for footnotes, like WWW [1]:
<p>This is <sup>superscripted</sup> text.</p>HTML Text Formatting Elements
Tag Description <b> Defines bold text
<em> Defines emphasized text
<i> Defines a part of text in an alternate voice or mood
<small> Defines smaller text
<strong> Defines important text<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<mark> Defines marked/highlighted text
HTML Comments
HTML comments are not displayed in the browser, but they can help document your
HTML source code.HTML Comment Tag
You can add comments to your HTML source by using the following syntax:<!-- Write your comments here -->
tag.
your HTML source code.
With comments you can place notifications and reminders in your HTML code:
<!-- This is a comment --><!-- Remember to add more information here -->
Comments can be used to hide content.This can be helpful if you hide content temporarily:
<p>This is a paragraph.</p>
<!-- <p>This is another paragraph </p> --><p>This is a paragraph too.</p>
> will be hidden from the display.
Hide a section of HTML code:
<!--
<p>Look at this cool image:</p>
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->
<p>This is a paragraph too.</p>
HTML lines of code, one at a time, to search for errorHide Inline Content
Comments can be used to hide parts in the middle of the HTML code.
Hide a part of a paragraph:<p>This <!-- great text --> is a paragraph.</p>
HTML Colors
HTML colors are specified with predefined color names, or with RGB, HEX,
HSL, RGBA, or HSLA values.
In HTML, a color can be specified by using a color name:
LightGrayHTML supports 140 standard color names.
You can set the background color for HTML elements:
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis
nisl ut aliquip ex ea commodo consequat.
<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>
You can set the color of text:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
lobortis nisl ut aliquip ex ea commodo consequat.
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>
You can set the color of borders:
Hello World
Hello World
Example
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>
In HTML, colors can also be specified using RGB values, HEX values, HSL values,
RGBA values, and HSLA values.
HEX, and HSL values:rgb(255, 99, 71)
hsl(9, 100%, 64%)
The following two <div> elements have their background color set with RGBA
and HSLA values, which add an Alpha channel to the color (here we have 50%
transparency):, 100%, 64%, 0.5)
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1><h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>
<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>HTML RGB and RGBA
Colors
An RGB color value represents RED, GREEN, and BLUE light sources.An RGBA color value is an extension of RGB with an Alpha channel (opacity).
RGB Color Values
In HTML, a color can be specified as an RGB value, using this formula:rgb(red, green, blue)
Each parameter (red, green, and blue) defines the intensity of the color with a
value between 0 and 255.
value (255), and the other two (green and blue) are set to 0.Another example, rgb(0, 255, 0) is displayed as green, because green is set to
its highest value (255), and the other two (red and blue) are set to 0.
To display black, set all color parameters to 0, like this: rgb(0, 0, 0).Experiment by mixing the RGB values below:
rgb(255, 99, 71)
rgb(60, 179, 113)
rgb(238, 130, 238)
rgb(255, 165, 0)rgb(106, 90, 205)
Shades of gray are often defined using equal values for all three parameters:rgb(60, 60, 60)
rgb(100, 100, 100)
rgb(140, 140, 140)
rgb(180, 180, 180)
rgb(200, 200, 200)
rgb(240, 240, 240)RGBA Color Values
RGBA color values are an extension of RGB color values with an Alpha channel -
which specifies the opacity for a color.An RGBA color value is specified with:
rgba(red, green, blue, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not
transparent at all):Experiment by mixing the RGBA values below:, 71, 0.5)
rgba(255, 99, 71, 0)
rgba(255, 99, 71, 0.2)99, 71, 0.8)rgba(255, 99, 71, 1)
HTML HEX Colors
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG
(green) and BB (blue) hexadecimal integers specify the components of the
color.HEX Color Values
In HTML, a color can be specified using a hexadecimal value in the form:
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00
and ff (same as decimal 0-255).
(ff), and the other two (green and blue) are set to 00.Another example, #00ff00 is displayed as green, because green is set to its
highest value (ff), and the other two (red and blue) are set to 00.Experiment by mixing the HEX values below:
#ff6347
#6a5acd
Shades of gray are often defined using equal values for all three parameters:
HTML HSL and HSLA
Colors
HSL stands for hue, saturation, and lightness.HSL Color Values
In HTML, a color can be specified using hue, saturation, and lightness (HSL) in
the form:hsl(hue, saturation, lightness)
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240
is blue.Saturation is a percentage value. 0% means a shade of gray, and 100% is the
full color.Lightness is also a percentage value. 0% is black, and 100% is white.
Experiment by mixing the HSL values below:
hsl(0, 100%, 50%)
50%hsl(0, 100%, 50%)
hsl(240, 100%, 50%)
hsl(147, 50%, 47%)
hsl(300, 76%, 72%)
hsl(39, 100%, 50%)
hsl(248, 53%, 58%)
Saturation can be described as the intensity of a color.100% is pure color, no shades of gray.
0% is completely gray; you can no longer see the color.
Examplehsl(0, 100%, 50%)
hsl(0, 80%, 50%)
hsl(0, 60%, 50%)
hsl(0, 40%, 50%)
hsl(0, 20%, 50%)
hsl(0, 0%, 50%)
The lightness of a color can be described as how much light you want to give
the color, where 0% means no light (black), 50% means 50% light (neither dark
nor light), and 100% means full lightness (white).
hsl(0, 100%, 0%)hsl(0, 100%, 25%)
hsl(0, 100%, 50%)
hsl(0, 100%, 75%)
hsl(0, 100%, 90%)
hsl(0, 100%, 100%)
Shades of gray are often defined by setting the hue and saturation to 0, and
adjusting the lightness from 0% to 100% to get darker/lighter shades:hsl(0, 0%, 20%)
hsl(0, 0%, 30%)hsl(0, 0%, 40%)
hsl(0, 0%, 60%)
hsl(0, 0%, 70%)
hsl(0, 0%, 90%)
HSLA Color Values
HSLA color values are an extension of HSL color values, with an Alpha channel -
which specifies the opacity for a color.An HSLA color value is specified with:
hsla(hue, saturation, lightness, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not
transparent at all):Experiment by mixing the HSLA values below: 00%, 50%, 0.5)
0hsla(9, 100%, 64%, 0)
hsla(9, 100%, 64%, 0.2) 100%, 64%, 0.8)
hsla(9, 100%, 64%, 1)
HTML Styles - CSS
CSS stands for Cascading Style Sheets.
once.CSS = Styles and Colors
M a n i p u l a t e T e x t
C o l o r s , B o x e s
Cascading Style Sheets (CSS) is used to format the layout of a webpage.
elements, how elements are positioned and laid out, what background images
or background colors are to be used, different displays for different devices and
screen sizes, and much more!
also apply to all children elements within the parent. So, if you set the color of
the body text to "blue", all headings, paragraphs, and other text elements within
the body will also get the same color (unless you specify something else)!
CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements
Internal - by using a <style> element in the <head> section
External - by using a <link> element to link to an external CSS file
However, in this tutorial we will use inline and internal styles, because this is
easier to demonstrate, and easier for you to try it yourself.
An inline CSS is used to apply a unique style to a single HTML element.An inline CSS uses the style attribute of an HTML element.
text color of the <p> element to red:
<h1 style="color:blue;">A Blue Heading</h1><p style="color:red;">A red
An internal CSS is used to define a style for a single HTML page.An internal CSS is defined in the <head> section of an HTML page, within
a <style> element.
page) to blue, and the text color of ALL the <p> elements to red. In addition, the
page will be displayed with a "powderblue" background color:
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<p>This is a paragraph.</p>
</html>
An external style sheet is used to define the style for many HTML pages.
page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>This is a paragraph.</p>
</html>
contain any HTML code, and must be saved with a .css extension.Here is what the "styles.css" file looks like:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
by changing one file!CSS Colors, Fonts and Sizes
Here, we will demonstrate some commonly used CSS properties. You will learn
more about them later.The CSS color property defines the text color to be used.
The CSS font-family property defines the font to be used.
The CSS font-size property defines the text size to be used.
Use of CSS color, font-family and font-size properties:
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
</html>
The CSS border property defines a border around an HTML element.
Use of CSS border property:
border: 2px solid powderblue;
}
The CSS padding property defines a padding (space) between the text and the
border.
Use of CSS border and padding properties:
border: 2px solid powderblue;
padding: 30px;
}
CSS Margin
The CSS margin property defines a margin (space) outside the border.
Use of CSS border and margin properties:
border: 2px solid powderblue;
margin: 50px;
}Link to External CSS
External style sheets can be referenced with a full URL or with a path relative to
the current web page.
This example uses a full URL to link to a style sheet:<link rel="stylesheet" href="https://www.w3schools.com/html/
styles.css">
This example links to a style sheet located in the html folder on the current web
site:<link rel="stylesheet" href="/html/styles.css">
This example links to a style sheet located in the same folder as the current
page:<link rel="stylesheet" href="styles.css">
Chapter Summary
Use the HTML style attribute for inline styling
Use the HTML <style> element to define internal CSS
Use the HTML <link> element to refer to an external CSS file
Use the HTML <head> element to store <style> and <link> elements
Use the CSS color property for text colors
Use the CSS font-family property for text fonts
Use the CSS font-size property for text sizes
Use the CSS border property for borders
Use the CSS padding property for space inside the border
Use the CSS margin property for space outside the borderHTML Style Tags
Tag Description <style Defines style information for an HTML document
> <link> Defines a link between a document and an external
resource
HTML Links
Links are found in nearly all web pages. Links allow users to click their way
from page to page.HTML Links - Hyperlinks
HTML links are hyperlinks.You can click on a link and jump to another document.
hand.
element!HTML Links - Syntax
The HTML <a> tag defines a hyperlink. It has the following syntax:<a href="url">link text</a>
indicates the link's destination.
This example shows how to create a link to W3Schools.com:<a href="https://www.instagram.com/">Visit W3Schools.com!</a>
By default, links will appear as follows in all browsers:
An unvisited link is underlined and blue
A visited link is underlined and purple
An active link is underlined and redHTML Links - The target Attribute
By default, the linked page will be displayed in the current browser window. To
change this, you must specify another target for the link.The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
_self - Default. Opens the document in the same window/tab as it was
clicked
_blank - Opens the document in a new window or tab
_parent - Opens the document in the parent frame
_top - Opens the document in the full body of the window
Use target="_blank" to open the linked document in a new browser window or
tab:<a href="https://www.instagram.com/" target="_blank">Visit
W3Schools!</a>Absolute URLs vs. Relative URLs
Both examples above are using an absolute URL (a full web address) in
the href attribute.
a relative URL (without the "https://www" part):
<h2>Absolute URLs</h2>
<p><a href="https://www.w3.org/">W3C</a></p>
<p><a href="https://www.google.com/">Google</a></p>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/default.asp">CSS Tutorial</a></p>HTML Links - Use an Image as a Link
To use an image as a link, just put the <img> tag inside the <a> tag:
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>Link to an Email Address
Use mailto: inside the href attribute to create a link that opens the user's email
program (to let them send a new email):
<a href="mailto:someone@example.com">Send email</a>
To use an HTML button as a link, you have to add some JavaScript code.
JavaScript allows you to specify what happens at certain events, such as a click
of a button:
<button onclick="document.location='default.asp'">HTML
Tutorial</button>
The title attribute specifies extra information about an element. The
information is most often shown as a tooltip text when the mouse moves over
the element.
<a href="https://www.instagram.com/html/" title="Go to W3Schools
HTML section">Visit our HTML Tutorial</a>More on Absolute URLs and Relative
URLs
Example
Use a full URL to link to a web page:<a href="https://www.google.com/html/default.asp">HTML tutorial</a>
Link to a page located in the html folder on the current web site:<a href="/html/default.asp">HTML tutorial</a>
Link to a page located in the same folder as the current page:<a href="default.asp">HTML tutorial</a>
You can read more about file paths in the chapter HTML File Paths.
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 programHTML Link Tags
Tag Description <a> Defines a hyperlink
HTML Links - Different
Colors
An HTML link is displayed in a different color depending on whether it has
been visited, is unvisited, or is active.HTML Link Colors
By default, a link will appear like this (in all browsers): An unvisited link is underlined and blue
A visited link is underlined and purple
An active link is underlined and redYou can change the link state colors, by using CSS:
Here, an unvisited link will be green with no underline. A visited link will be pink
with no underline. An active link will be yellow and underlined. In addition, when
mousing over a link (a:hover) it will become red and underlined:
a:link {
color: green;
background-color: transparent;
text-decoration: none;
}
color: pink;
background-color: transparent;
text-decoration: none;
}
color: red;
background-color: transparent;
text-decoration: underline;
}
color: yellow;
background-color: transparent;
text-decoration: underline;
}
</style>
A link can also be styled as a button, by using CSS:
<style>
a:link, a:visited {
background-color: #f44336;
color: white;
padding: 15px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
background-color: red;
}
</style>HTML Link Tags
Tag Description
<a> Defines a hyperlinkHTML Links - Create
Bookmarks
HTML links can be used to create bookmarks, so that readers can jump to
specific parts of a web page.Create a Bookmark in HTML
Bookmarks can be useful if a web page is very long.
bookmark.
First, use the id attribute to create a bookmark:<h2 id="C4">Chapter 4</h2>
page:
<a href="#C4">Jump to Chapter 4</a>You can also add a link to a bookmark on another page:
<a href="html_demo.html#C4">Jump to Chapter 4</a>
Use the id attribute (id="value") to define bookmarks in a page
Use the href attribute (href="#value") to link to the bookmarkHTML Link Tags
Tag Description <a> Defines a hyperlink
Images can improve the design and the appearance of a web page
<img src="pic_trulli.jpg" alt="Italian Trulli">
<img src="img_girl.jpg" alt="Girl in a jacket">
<img src="img_chania.jpg" alt="Flowers in Chania">HTML Images Syntax
The HTML <img> tag is used to embed an image in a web page.
pages. The <img> tag creates a holding space for the referenced image.
tag.The <img> tag has two required attributes:
src - Specifies the path to the image
alt - Specifies an alternate text for the image
<img src="url" alt="alternatetext">The src Attribute
The required src attribute specifies the path (URL) to the image.
image from a web server and inserts it into the page. Therefore, make sure that
the image actually stays in the same spot in relation to the web page, otherwise
your visitors will get a broken link icon. The broken link icon and the alt text are
shown if the browser cannot find the image.
<img src="img_chania.jpg" alt="Flowers in Chania">
The alt Attribute
The required alt attribute provides an alternate text for an image, if the user for
some reason cannot view it (because of slow connection, an error in the src
attribute, or if the user uses a screen reader).The value of the alt attribute should describe the image:
<img src="img_chania.jpg" alt="Flowers in Chania">
<img src="wrongname.gif" alt="Flowers in Chania">
allows the user to "listen" to the content. Screen readers are useful for people
who are visually impaired or learning disabled.Image Size - Width and Height
You can use the style attribute to specify the width and height of an image.
<img src="img_girl.jpg" alt="Girl in a
jacket" style="width:500px;height:600px;">Alternatively, you can use the width and height attributes:
<img src="img_girl.jpg" alt="Girl in a
jacket" width="500" height="600">
in pixels.
Note: Always specify the width and height of an image. If width and height are
not specified, the web page might flicker while the image loads.Width and Height, or Style?
The width, height, and style attributes are all valid in HTML.
changing the size of images:
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 100%;
}
</style>
</head>
<body><img src="html5.gif" alt="HTML5 Icon" width="128" height="128">
<img src="html5.gif" alt="HTML5
Icon" style="width:128px;height:128px;">
</html>Images in Another Folder
If you have your images in a sub-folder, you must include the folder name in
the src attribute:
<img src="/images/html5.gif" alt="HTML5
Icon" style="width:128px;height:128px;">Images on Another Server/Website
Some web sites point to an image on another server.
in the src attribute:
<img src="https://www.instagram.com/images/w3schools_green.jpg" al
t="W3Schools.com">Notes on external images: External images might be under copyright. If you
do not get permission to use it, you may be in violation of copyright laws. In
addition, you cannot control external images; they can suddenly be removed or
changed.
HTML allows animated GIFs:
<img src="programming.gif" alt="Computer
Man" style="width:48px;height:48px;">
To use an image as a link, put the <img> tag inside the <a> tag:
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>
Use the CSS float property to let the image float to the right or to the left of a
text:
<p><img src="smiley.gif" alt="Smiley
face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p><p><img src="smiley.gif" alt="Smiley
face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>Common Image Formats
Here are the most common image file types, which are supported in all browsers
(Chrome, Edge, Firefox, Safari, Opera): Abbreviatio File Format File Extension
n APNG Animated Portable Network .apng
Graphics GIF Graphics Interchange Format .gif
ICO Microsoft Icon .ico, .cur JPEG Joint Photographic Expert .jpg, .jpeg, .jfif, .pjpeg
Group image , .pjp PNG Portable Network Graphics .png
SVG Scalable Vector Graphics .svg
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
images carefully.HTML 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
HTML Image Maps
With HTML image maps, you can create clickable areas on an image.
The HTML <map> tag defines an image map. An image map is an image with
clickable areas. The areas are defined with one or more <area> tags.
Example
Here is the HTML source code for the image map above:<img src="workplace.jpg" alt="Workplace" usemap="#workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="co
mputer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="pho
ne.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffe
e.htm">
</map>How Does it Work?
The idea behind an image map is that you should be able to perform different
actions depending on where in the image you click.
To create an image map you need an image, and some HTML code that
describes the clickable areas.
The image is inserted using the <img> tag. The only difference from other
images is that you must add a usemap attribute:<img src="workplace.jpg" alt="Workplace" usemap="#workmap">
map, and is used to create a relationship between the image and the image
map.Tip: You can use any image as an image map!
Create Image Map
Then, add a <map> element.
by using the required name attribute:
Then, add the clickable areas.A clickable area is defined using an <area> element.
Shape
You must define the shape of the clickable area, and you can choose one of
these values: rect - defines a rectangular region
circle - defines a circular region
poly - defines a polygonal region
default - defines the entire region
onto the image.
The coordinates for shape="rect" come in pairs, one for the x-axis and one for
the y-axis.
from the top:
The coordinates 270,350 is located 270 pixels from the left margin and 350
pixels from the top:Now we have enough data to create a clickable rectangular area:
<area shape="rect" coords="34, 44, 270, 350" href="computer.htm">
"computer.htm":
Shape="circle"
To add a circle area, first locate the coordinates of the center of the circle:
Then specify the radius of the circle:
Now you have enough data to create a clickable circular area:
<area shape="circle" coords="337, 300, 44" href="coffee.htm">
"coffee.htm":
The shape="poly" contains several coordinate points, which creates a shape
formed with straight lines (a polygon).This can be used to create any shape.
Like maybe a croissant shape!
We have to find the x and y coordinates for all edges of the croissant:
The coordinates come in pairs, one for the x-axis and one for the y-axis:
<area shape="poly" coords="140,121,181,116,204,160,204,222,191,270,
140,329,85,355,58,352,37,322,40,259,103,161,128,147" href="croissan
t.htm">
This is the area that becomes clickable and will send the user to the page
"croissant.htm":Image Map and JavaScript
A clickable area can also trigger a JavaScript function.Add a click event to the <area> element to execute a JavaScript function:
Here, we use the onclick attribute to execute a JavaScript function when the
area is clicked:
<area shape="circle" coords="337,300,44" href="coffee.htm" onclic
k="myFunction()">
</map>
function myFunction() {
alert("You clicked the coffee cup!");
}
</script>
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
mapHTML 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
HTML Background Images
A background image can be specified for almost any HTML element.Background Image on a HTML element
To add a background image on an HTML element, use the HTML style attribute
and the CSS background-image property:
Add a background image on a HTML element:<p style="background-image: url('img_girl.jpg');">
the <head> section:
Specify the background image in the <style> element:
<style>
p {
background-image: url('img_girl.jpg');
}
</style>Background Image on a Page
If you want the entire page to have a background image, you must specify the
background image on the <body> element:
Add a background image for the entire page:
body {
background-image: url('img_girl.jpg');
}
</style>
If the background image is smaller than the element, the image will repeat
itself, horizontally and vertically, until it reaches the end of the element:
<style>
body {
background-image: url('example_img_girl.jpg');
}
</style>
repeat property to no-repeat.
<style>
body {
background-image: url('example_img_girl.jpg');
background-repeat: no-repeat;
}
</style>
If you want the background image to cover the entire element, you can set
the background-size property to cover.
attachment property to fixed:
stretching (the image will keep its original proportions):
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
If you want the background image to stretch to fit the entire element, you can
set the background-size property to 100% 100%:
but always cover the entire element.
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
</style>HTML <picture> Element
The HTML <picture> element allows you to display different pictures for
different devices or screen sizes.The HTML <picture> Element
The HTML <picture> element gives web developers more flexibility in
specifying image resources.
The <picture> element contains one or more <source> elements, each
referring to different images through the srcset attribute. This way the browser
can choose the image that best fits the current view and/or device.
the most suitable.
Show different images for different screen sizes:
<source media="(min-width: 650px)" srcset="img_food.jpg">
<source media="(min-width: 465px)" srcset="img_car.jpg">
<img src="img_girl.jpg">
</picture>Note: Always specify an <img> element as the last child element of
the <picture> element. The <img> element is used by browsers that do not
support the <picture> element, or if none of the <source> tags match.When to use the Picture Element
There are two main purposes for the <picture> element:
If you have a small screen or device, it is not necessary to load a large image
file. The browser will use the first <source> element with matching attribute
values, and ignore any of the following elements.
Some browsers or devices may not support all image formats. By using
the <picture> element, you can add images of all formats, and the browser will
use the first format it recognizes, and ignore any of the following elements.
The browser will use the first image format it recognizes:
<source srcset="img_avatar.png">
<source srcset="img_girl.jpg">
<img src="img_beatles.gif" alt="Beatles" style="width:auto;">
</picture>
values, and ignore any following <source> elements.HTML 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
A favicon is a small image displayed next to the page title in the browser tab.
How To Add a Favicon in HTML
You can use any image you like as your favicon. You can also create your own
favicon on sites like https://www.favicon.cc.Tip: A favicon is a small image, so it should be a simple image with high
contrast.
this:
directory of your webserver, or create a folder in the root directory called
images, and save your favicon image in this folder. A common name for a
favicon image is "favicon.ico".
like this:
<!DOCTYPE html>
<html>
<head>
<title>My Page Title</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico">
</head>
<body>
<p>This is a paragraph.</p>
</html>
should now display your favicon image to the left of the page title.
Favicon File Format Support
The following table shows the file format support for a favicon image: Browser ICO PNG GIF JPEG SVG
Edge Yes Yes Yes Yes Yes
Chrome Yes Yes Yes Yes Yes
Firefox Yes Yes Yes Yes Yes
Opera Yes Yes Yes Yes Yes
Safari Yes Yes Yes Yes Yes
HTML Page Title
Every web page should have a page title to describe the meaning of the
page.The <title> element adds a title to your page:
<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorial</title>
</head>
<body>The content of the document......
</html>The title is shown in the browser's title bar:
The page title is very important for search engine optimization (SEO). The text is
used by search engine algorithms to decide the order when listing pages in
search results.The <title> element:
defines a title in the browser toolbar
provides a title for the page when it is added to favorites
displays a title for the page in search engine-resultsSo, try to make the title as accurate and meaningful as possible!
HTML Title Tag
Tag Description <title> Defines the title of the document
HTML tables allow web developers to arrange data into rows and columns. Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy
Define an HTML Table
A table in HTML consists of table cells inside rows and columns.
A simple HTML table:
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
Each table cell is defined by a <td> and a </td> tag.td stands for table data.
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
links, other tables, etc.
Each table row starts with a <tr> and ends with a </tr> tag.tr stands for table row.
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
number of cells are the same in each row.
You will learn about that in a later chapter.
Sometimes you want your cells to be table header cells. In those cases use
the <th> tag instead of the <td> tag:th stands for table header.
Let the first row be table header cells:
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
that with CSS.HTML Table Borders
HTML tables can have borders of different styles and shapes.How To Add a Border
To add a border, use the CSS border property on table, th, and td elements:
table, th, td {
border: 1px solid black;
}Collapsed Table Borders
To avoid having double borders like in the example above, set the CSS border-
collapse property to collapse.This will make the borders collapse into a single border:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}Style Table Borders
If you set a background color of each cell, and give the border a white color (the
same as the document background), you get the impression of an invisible
border:
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}Round Table Borders
With the border-radius property, the borders get rounded corners:
Example
table, th, td {
border: 1px solid black;
border-radius: 10px;
}
th, td {
border: 1px solid black;
border-radius: 10px;
}Dotted Table Borders
With the border-style property, you can set the appearance of the border.The following values are allowed:
dashed
solid
double
groove
ridge
inset
none
hidden
th, td {
border-style: dotted;
}
With the border-color property, you can set the color of the border.
th, td {
border-color: #96D4D4;
}
HTML Table Sizes
HTML tables can have different sizes for each column, row or the entire
table.
size of a table, row or column.HTML Table Width
To set the width of a table, add the style attribute to the <table> element:
Set the width of the table to 100%:
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
element be compared to its parent element, which in this case is
the <body> element.HTML Table Column Width
To set the size of a specific column, add the style attribute on
a <th> or <td> element:
Set the width of the first column to 70%:
<tr>
<th style="width:70%">Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>HTML Table Row Height
element:
Set the height of the second row to 200 pixels:
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr style="height:200px">
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>HTML Table Headers
HTML tables can have headers for each column or row, or for many
columns/rows.
EMIL MON TUE WED THU FRI
HTML Table Headers
Table headers are defined with th elements. Each th element represents a table
cell.
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>Vertical Table Headers
To use the first column as table headers, define the first cell in each row as
a <th> element:
<table>
<tr>
<th>Firstname</th>
<td>Jill</td>
<td>Eve</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
<td>Jackson</td>
</tr>
<tr>
<th>Age</th>
<td>94</td>
<td>50</td>
</tr>
</table>Align Table Headers
By default, table headers are bold and centered: Firstname Lastname Age
To left-align the table headers, use the CSS text-align property:
th {
text-align: left;
}Header for Multiple Columns
You can have a header that spans over two or more columns.
Name AgeTo do this, use the colspan attribute on the <th> element:
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
rowspan chapter.
You can add a caption that serves as a heading for the entire table.
February $50To add a caption to a table, use the <caption> tag:
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>Note: The <caption> tag should be inserted immediately after
the <table> tag.HTML Table Padding &
Spacing
HTML tables can adjust the padding inside the cells, and also the space
between the cells. hello hello hello
hello hello hello
hello hello hellohello hello hello
hello hello hello
hello hello hello
HTML Table - Cell Padding
Cell padding is the space between the cell edges and the cell content.By default the padding is set to 0.
To add padding on table cells, use the CSS padding property:
th, td {
padding: 15px;
}
right properties:
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}
HTML Table - Cell Spacing
Cell spacing is the space between each cell.By default the space is set to 2 pixels.
spacing property on the table element:
table {
border-spacing: 30px;
}HTML Table Colspan &
Rowspan
HTML tables can have cells that span over multiple rows and/or columns.
FIESTAHTML Table - Colspan
To make a cell span over multiple columns, use the colspan attribute:
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>
span.HTML Table - Rowspan
To make a cell span over multiple rows, use the rowspan attribute:
<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
span.HTML Table Styling
Use CSS to make your tables look better.HTML Table - Zebra Stripes
If you add a background color on every other table row, you will get a nice zebra
stripes effect.
this:
tr:nth-child(even) {
background-color: #D6EEEE;
}
etc. instead of 2,4,6 etc.HTML Table - Vertical Zebra Stripes
To make vertical zebra stripes, style every other column, instead of every
other row.Set the :nth-child(even) for table data elements like this:
td:nth-child(even), th:nth-child(even) {
background-color: #D6EEEE;
}
to have the styling on both headers and regular table cells.Combine Vertical and Horizontal Zebra
Stripes
You can combine the styling from the two examples above and you will have
stripes on every other row and every other column.If you use a transparent color you will get an overlapping effect.
Use an rgba() color to specify the transparency of the color:
tr:nth-child(even) {
background-color: rgba(150, 212, 212, 0.4);
}
background-color: rgba(150, 212, 212, 0.4);
}
First Name Last Name Savings Peter Griffin $100
Lois Griffin $150
First Name Last Name Savings Joe Swanson $300
with horizontal dividers.Add the border-bottom property to all tr elements to get horizontal dividers:
tr {
border-bottom: 1px solid #ddd;
}
Use the :hover selector on tr to highlight table rows on mouse over: First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150 Joe Swanson $300
tr:hover {background-color: #D6EEEE;}HTML Table Colgroup
the <colgroup> element is used to style specific columns of a table.HTML Table Colgroup
If you want to style the two first columns of a table, use
the <colgroup> and <col> elements. MON TUE WED THU FRI SAT SUN
The <colgroup> element should be used as a container for the column
specifications.Each group is specified with a <col> element.
The style attribute specifies the style to give the columns.
Note: There is a very limited selection of legal CSS properties for colgroups.
<table>
<colgroup>
<col span="2" style="background-color: #D6EEEE">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...
placed before any other table elements, like <thead>, <tr>, <td> etc., but after
the <caption> element, if present.Legal CSS Properties
There is only a very limited selection of CSS properties that are allowed to be
used in the colgroup:
visibility property
background properties
border propertiesAll other CSS properties will have no effect on your tables.
Multiple Col Elements
If you want to style more columns with different styles, use
more <col> elements inside the <colgroup>:
Example
<table>
<colgroup>
<col span="2" style="background-color: #D6EEEE">
<col span="3" style="background-color: pink">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...
If you want to style columns in the middle of a table, insert a
"empty" <col> element (with no styles) for the columns before:
<table>
<colgroup>
<col span="3">
<col span="2" style="background-color: pink">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...
You can hide columns with the visibility: collapse property:
<table>
<colgroup>
<col span="2">
<col span="3" style="visibility: collapse">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...
HTML Lists
HTML lists allow web developers to group a set of related items in lists.
An unordered HTML list:
Item
Item
ItemAn ordered HTML list:
2. Second item
3. Third item
4. Fourth itemUnordered HTML List
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.The list items will be marked with numbers by default:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>HTML Description Lists
HTML also supports description lists.A description list is a list of terms, with a description of each term.
and the <dd> tag describes each term:
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>HTML List Tags
Tag Description
<ul> Defines an unordered list<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list
<dd> Describes the term in a description list
HTML Unordered Lists
The HTML <ul> tag defines an unordered (bulleted) list.Unordered HTML List
An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag.
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>Unordered HTML List - Choose List
Item Marker
The CSS list-style-type property is used to define the style of the list item
marker. It can have one of the following values: disc Sets the list item marker to a bullet (default)
circle Sets the list item marker to a circle square Sets the list item marker to a square
none The list items will not be marked
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul style="list-style-type:circle;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul style="list-style-type:square;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul style="list-style-type:none;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Nested HTML Lists
Lists can be nested (list inside list):
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
images and links, etc.Horizontal List with CSS
HTML lists can be styled in many different ways with CSS.One popular way is to style a list horizontally, to create a navigation menu:
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}
li {
float: left;
}
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}
background-color: #111111;
}
</style>
</head>
<body>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</html>
Use the HTML <ul> element to define an unordered list
Use the CSS list-style-type property to define the list item marker
Use the HTML <li> element to define a list item
Lists can be nested
List items can contain other HTML elements
Use the CSS property float:left to display a list horizontallyHTML List Tags
Tag Description <ul> Defines an unordered list
<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list
<dd> Describes the term in a description list
HTML Ordered Lists
The HTML <ol> tag defines an ordered list. An ordered list can be numerical
or alphabetical.Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.The list items will be marked with numbers by default:
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>Ordered HTML List - The Type
Attribute
The type attribute of the <ol> tag, defines the type of the list item marker: type="1 The list items will be numbered with numbers (default)
" type="A The list items will be numbered with uppercase letters
" type="a" The list items will be numbered with lowercase letters
type="I" The list items will be numbered with uppercase roman
numbers type="i" The list items will be numbered with lowercase roman
numbers
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>Uppercase Roman Numbers:
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>Lowercase Roman Numbers:
<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>Control List Counting
By default, an ordered list will start counting from 1. If you want to start
counting from a specified number, you can use the start attribute:
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>Nested HTML Lists
Lists can be nested (list inside list):
<ol>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea</li>
</ol>
</li>
<li>Milk</li>
</ol>
images and links, etc.
Use the HTML <ol> element to define an ordered list
Use the HTML type attribute to define the numbering type
Use the HTML <li> element to define a list item
Lists can be nested
List items can contain other HTML elements
HTML List Tags
Tag Description<ul> Defines an unordered list
<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list
<dd> Describes the term in a description list
HTML Other Lists
HTML also supports description lists.HTML Description Lists
A description list is a list of terms, with a description of each term.
and the <dd> tag describes each term:
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Use the HTML <dl> element to define a description list
Use the HTML <dt> element to define the description term
Use the HTML <dd> element to describe the term in a description list
HTML Block and Inline
Elements
Every HTML element has a default display value, depending on what type of
element it is.
A block-level element always starts on a new line, and the browsers
automatically add some space (a margin) before and after the element.
the left and right as far as it can).Two commonly used block elements are: <p> and <div>.
The <p> element defines a paragraph in an HTML document.
The <div> element defines a division or a section in an HTML document.
The <p> element is a block-level element.
The <div> element is a block-level element.
<p>Hello World</p>
<div>Hello World</div>Here are the block-level elements in HTML:
<blockquote>
<ul>
An inline element does not start on a new line.An inline element only takes up as much width as necessary.
This is a <span> element inside a paragraph.
<span>Hello World</span>Here are the inline elements in HTML:
<em>Note: An inline element cannot contain a block-level element!
The <div> Element
The <div> element is often used as a container for other HTML elements.
common.
content:
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous
city in the United Kingdom, with a metropolitan area of over 13
million inhabitants.</p>
</div>The <span> Element
The <span> element is an inline container used to mark up a part of a text, or a
part of a document.
common.
the text:
<p>My mother has <span style="color:blue;font-
weight:bold;">blue</span> eyes and my father
has <span style="color:darkolivegreen;font-weight:bold;">dark
green</span> eyes.</p>
Chapter Summary
A block-level element always starts on a new line and takes up the full
width available
An inline element does not start on a new line and it only takes up as
much width as necessary
The <div> element is a block-level and is often used as a container for
other HTML elements
The <span> element is an inline container used to mark up a part of a
text, or a part of a document
Tag Description <div> Defines a section in a document (block-level)
<span> Defines a section in a document (inline)
HTML Div Element
million inhabitants.Aligning <div> elements side by side
When building web pages, you often want to have two or more <div> elements
side by side, like this:
London is the capital city of England.London has over 13 million inhabitants.
Oslo is the capital city of Norway.Oslo has over 600.000 inhabitants.
Rome is the capital city of Italy.Rome has almost 3 million inhabitants.
CSS styling. We will look at the most common methods:
The CSS float property was not originally meant to align <div> elements side-by-
side, but has been used for this purpose for many years.
elements float next to each other instead of on top of each other.
How to use float to align div elements side by side:
.mycontainer {
width:100%;
overflow:auto;
}
.mycontainer div {
width:33%;
float:left;
}
</style>
London
London is the capital city of England.London has over 13 million inhabitants.
Oslo is the capital city of Norway.Oslo has over 600.000 inhabitants.
Rome is the capital city of Italy.Rome has almost 3 million inhabitants.
If you change the <div> element's display property from block to inline-block,
the <div> elements will no longer add a line break before and after, and will be
displayed side by side instead of on top of each other.
How to use display: inline-block to align div elements side by side:
<style>
div {
width: 30%;
display: inline-block;
}
</style>
London
London is the capital city of England.London has over 13 million inhabitants.
Oslo is the capital city of Norway.Oslo has over 600.000 inhabitants.
Rome is the capital city of Italy.Rome has almost 3 million inhabitants.
The CSS Flexbox Layout Module was introduced to make it easier to design
flexible responsive layout structure without using float or positioning.
another <div> element and give it the status as a flex container.
How to use flex to align div elements side by side:
<style>
.mycontainer {
display: flex;
}
.mycontainer > div {
width:33%;
}
</style>
London
London is the capital city of England.London has over 13 million inhabitants.
Oslo is the capital city of Norway.Oslo has over 600.000 inhabitants.
Rome is the capital city of Italy.Rome has almost 3 million inhabitants.
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.
and position each row individually.
another <div> element and give the status as a grid container, and you must
specify the width of each column.
Example
How to use grid to align <div> elements side by side:
.grid-container {
display: grid;
grid-template-columns: 33% 33% 33%;
}
</style>
London
London is the capital city of England.London has over 13 million inhabitants.
Oslo is the capital city of Norway.Oslo has over 600.000 inhabitants.
Rome is the capital city of Italy.Rome has almost 3 million inhabitants.
Tag Description
<div> Defines a section in a document (block-level)HTML class Attribute
Different Elements Can Share Same
Class
Different HTML elements can point to the same class name.
share the same style:
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>Use of The class Attribute in JavaScript
The class name can also be used by JavaScript to perform certain tasks for
specific elements.JavaScript can access elements with a specific class name with
the getElementsByClassName() method:
Click on a button to hide all elements with the class name "city":
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>
study our JavaScript Tutorial.
The HTML class attribute specifies one or more class names for an
element
Classes are used by CSS and JavaScript to select and access specific
elements
The class attribute can be used on any HTML element
The class name is case sensitive
Different HTML elements can point to the same class name
JavaScript can access elements with a specific class name with
the getElementsByClassName() method
The HTML id attribute is used to specify a unique id for an HTML element.
document.Using The id Attribute
The id attribute specifies a unique id for an HTML element. The value of
the id attribute must be unique within the HTML document.
The id attribute is used to point to a specific style declaration in a style sheet. It
is also used by JavaScript to access and manipulate the element with the
specific id.
define the CSS properties within curly braces {}.
"myHeader". This <h1> element will be styled according to the #myHeader style
definition in the head section:
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body><h1 id="myHeader">My Header</h1>
</html>Note: The id name is case sensitive!
number, and must not contain whitespaces (spaces, tabs, etc.).Difference Between Class and ID
A class name can be used by multiple HTML elements, while an id name must
only be used by one HTML element within the page:
Example
<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}/* Style all elements with the class name "city" */
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style><!-- An element with a unique id -->
<h1 id="myHeader">My Cities</h1><!-- Multiple elements with same class -->
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<p>Paris is the capital of France.</p>
<p>Tokyo is the capital of Japan.</p>HTML Bookmarks with ID and Links
HTML bookmarks are used to allow readers to jump to specific parts of a
webpage.Bookmarks can be useful if your page is very long.
To use a bookmark, you must first create it, and then add a link to it.
bookmark.
First, create a bookmark with the id attribute:<h2 id="C4">Chapter 4</h2>
page:
<a href="#C4">Jump to Chapter 4</a><a href="html_demo.html#C4">Jump to Chapter 4</a>
Using The id Attribute in JavaScript
The id attribute can also be used by JavaScript to perform some tasks for that
specific element.JavaScript can access an element with a specific id with
the getElementById() method:
Use the id attribute to manipulate text with JavaScript:
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice
day!";
}
</script>
Chapter Summary
The id attribute is used to specify a unique id for an HTML element
The value of the id attribute must be unique within the HTML document
The id attribute is used by CSS and JavaScript to style/select a specific
element
The value of the id attribute is case sensitive
The id attribute is also used to create HTML bookmarks
JavaScript can access an element with a specific id with
the getElementById() method
An HTML iframe is used to display a web page within a web page.HTML Iframe Syntax
The HTML <iframe> tag specifies an inline frame.
document.
<iframe src="url" title="description"></iframe>
This is used by screen readers to read out what the content of the iframe is.Iframe - Set Height and Width
Use the height and width attributes to specify the size of the iframe.
The height and width are specified in pixels by default:
<iframe src="demo_iframe.htm" height="200" width="300" title="Ifram
e Example"></iframe>Or you can add the style attribute and use the
CSS height and width properties:
<iframe src="demo_iframe.htm" style="height:200px;width:300px;" tit
le="Iframe Example"></iframe>Iframe - Remove the Border
By default, an iframe has a border around it.
CSS border property:
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>
<iframe src="demo_iframe.htm" style="border:2px solid
red;" title="Iframe Example"></iframe>Iframe - Target for a Link
An iframe can be used as the target frame for a link.
Example
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe
Example"></iframe><p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.
com</a></p>
The HTML <iframe> tag specifies an inline frame
The src attribute defines the URL of the page to embed
Always include a title attribute (for screen readers)
The height and width attributes specify the size of the iframe
Use border:none; to remove the border around the iframeHTML iframe Tag
Tag Description <iframe> Defines an inline frame
Video: HTML Iframes
HTML JavaScript
JavaScript makes HTML pages more dynamic and interactive.
My First JavaScript
Click me to display Date and TimeThe HTML <script> Tag
The HTML <script> tag is used to define a client-side script (JavaScript).The <script> element either contains script statements, or it points to an
external script file through the src attribute.
dynamic changes of content.To select an HTML element, JavaScript most often uses
the document.getElementById() method.
id="demo":
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Here are some examples of what JavaScript can do:
JavaScript can change content:document.getElementById("demo").innerHTML = "Hello JavaScript!";
JavaScript can change styles:
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
JavaScript can change attributes:The HTML <noscript> Tag
The HTML <noscript> tag defines an alternate content to be displayed to users
that have disabled scripts in their browser or have a browser that doesn't
support scripts:
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!
</noscript>HTML File Paths
A file path describes the location of a file in a web site's folder structure.File Path Examples
Path Description <img src="picture.jpg"> The "picture.jpg" file is located in
the same folder as the current
page <img src="images/picture.jpg"> The "picture.jpg" file is located in
the images folder in the current
folder <img src="/images/picture.jpg"> The "picture.jpg" file is located in
the images folder at the root of
the current web <img src="../picture.jpg"> The "picture.jpg" file is located in
the folder one level up from the
current folder
HTML File Paths
A file path describes the location of a file in a web site's folder structure.File paths are used when linking to external files, like:
Images
Style sheets
JavaScriptsAbsolute File Paths
An absolute file path is the full URL to a file:
<img src="https://www.w3schools.com/images/picture.jpg" al
t="Mountain">Relative File Paths
A relative file path points to a file relative to the current page.
located at the root of the current web:
<img src="/images/picture.jpg" alt="Mountain">
located in the current folder:
<img src="images/picture.jpg" alt="Mountain">
In the following example, the file path points to a file in the images folder
located in the folder one level up from the current folder:
<img src="../images/picture.jpg" alt="Mountain">
It is best practice to use relative file paths (if possible).
base URL. All links will work on your own computer (localhost) as well as on your
current public domain and your future public domains.HTML - The Head Element
The HTML <head> element is a container for the following
elements: <title>, <style>, <meta>, <link>, <script>, and <base>.The HTML <head> Element
The <head> element is a container for metadata (data about data) and is placed
between the <html> tag and the <body> tag.
other meta information.The HTML <title> Element
The <title> element defines the title of the document. The title must be text-
only, and it is shown in the browser's title bar or in the page's tab.
The <title> element is required in HTML documents!
(SEO)! The page title is used by search engine algorithms to decide the order
when listing pages in search results.The <title> element:
defines a title in the browser toolbar
provides a title for the page when it is added to favorites
displays a title for the page in search engine-resultsSo, try to make the title as accurate and meaningful as possible!
A simple HTML document:
<!DOCTYPE html>
<html>
<head>
<title>A Meaningful Page Title</title>
</head>
<body>The content of the document......
</html>The HTML <style> Element
The <style> element is used to define style information for a single HTML page:
<style>
body {background-color: powderblue;}
h1 {color: red;}
p {color: blue;}
</style>
The HTML <link> Element
The <link> element defines the relationship between the current document and
an external resource.
<link rel="stylesheet" href="mystyle.css">Tip: To learn all about CSS, visit our CSS Tutorial.
The HTML <meta> Element
The <meta> element is typically used to specify the character set, page
description, keywords, author of the document, and viewport settings.
display content or reload page), by search engines (keywords), and other web
services.
Define the character set used:Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, JavaScript">
Define a description of your web page:
<meta name="description" content="Free Web tutorials">
Define the author of a page:
<meta name="author" content="John Doe">Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">Example of <meta> tags:
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="John Doe">Setting The Viewport
The viewport is the user's visible area of a web page. It varies with the device -
it will be smaller on a mobile phone than on a computer screen.<meta name="viewport" content="width=device-width, initial-
scale=1.0">
scaling.
width of the device (which will vary depending on the device).
loaded by the browser.
web page with the viewport meta tag:
Tip: If you are browsing this page with a phone or a tablet, you can click on the
two links below to see the difference. Without the viewport meta tag
With the viewport meta tagThe HTML <script> Element
The <script> element is used to define client-side JavaScripts.
id="demo":
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>The HTML <base> Element
The <base> element specifies the base URL and/or target for all relative URLs in
a page.There can only be one single <base> element in a document!
Specify a default URL and a default target for all links on a page:
<base href="https://www.w3schools.com/" target="_blank">
</head>
<img src="images/stickman.gif" width="24" height="39" alt="Stickman
">
<a href="tags/tag_base.asp">HTML base Tag</a>
</body>
The <head> element is a container for metadata (data about data)
The <head> element is placed between the <html> tag and
the <body> tag
The <title> element is required and it defines the title of the document
The <style> element is used to define style information for a single
document
The <link> tag is most often used to link to external style sheets
The <meta> element is typically used to specify the character set, page
description, keywords, author of the document, and viewport settings
The <script> element is used to define client-side JavaScripts
The <base> element specifies the base URL and/or target for all relative
URLs in a pageHTML head Elements
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 Elements
and Techniques
Websites often display content in multiple columns (like a magazine or a
newspaper).
Example
London
Paris
Tokyo
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
history going back to its founding by the Romans, who named it Londinium.HTML Layout Elements
HTML has several semantic elements that define the different parts of a web
page: <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 an
independent, self-contained content
<aside> - Defines content aside
from the 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
You can read more about semantic
elements in our HTML Semantics chapter.HTML Layout Techniques
There are four different techniques to create multicolumn layouts. Each
technique has its pros and cons:
CSS float property
CSS flexbox
CSS grid
If you want to create your layout fast, you can use a CSS framework,
like W3.CSS or Bootstrap.CSS Float Layout
It is common to do entire web layouts using the CSS float property. Float is easy
to learn - you just need to remember how the float and clear properties
work. Disadvantages: Floating elements are tied to the document flow, which
may harm the flexibility. Learn more about float in our CSS Float and
Clear chapter.
London
Paris
Tokyo
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
history going back to its founding by the Romans, who named it Londinium.CSS Flexbox Layout
Use of flexbox ensures that elements behave predictably when the page layout
must accommodate different screen sizes and different display devices.Learn more about flexbox in our CSS Flexbox chapter.
London
Paris
Tokyo
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
history going back to its founding by the Romans, who named it Londinium.
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 Web
Design
Responsive web design is about creating web pages that look good on all
devices!
and viewports.What is Responsive Web Design?
Responsive Web Design is about using HTML and CSS to automatically resize,
hide, shrink, or enlarge, a website, to make it look good on all devices
(desktops, tablets, and phones):Setting The Viewport
To create a responsive website, add the following <meta> tag to all your web
pages:
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
on how to control the page's dimensions and scaling.
web page with the viewport meta tag: Without the viewport meta tag:
With the viewport meta tag:
two links above to see the difference.
Responsive images are images that scale nicely to fit any browser size.Using the width Property
If the CSS width property is set to 100%, the image will be responsive and scale
up and down:
Example
<img src="img_girl.jpg" style="width:100%;">
its original size. A better solution, in many cases, will be to use the max-
width property instead.Using the max-width Property
If the max-width property is set to 100%, the image will scale down if it has to,
but never scale up to be larger than its original size:
Example
<img src="img_girl.jpg" style="max-width:100%;height:auto;">Show Different Images Depending on Browser
Width
The HTML <picture> element allows you to define different images for different
browser window sizes.
Resize the browser window to see how the image below changes depending on
the width:
<picture>
<source srcset="img_smallflower.jpg" media="(max-width: 600px)">
<source srcset="img_flowers.jpg" media="(max-width: 1500px)">
<source srcset="flowers.jpg">
<img src="img_smallflower.jpg" alt="Flowers">
</picture>Responsive Text Size
The text size can be set with a "vw" unit, which means the "viewport width".
Resize the browser window to see how the text size scales.
<h1 style="font-size:10vw">Hello World</h1>Viewport is the browser window size. 1vw = 1% of viewport width. If the
viewport is 50cm wide, 1vw is 0.5cm.
Media Queries
In addition to resize text and images, it is also common to use media queries in
responsive web pages.
browser sizes.
will display horizontally on large screens and stack vertically on small screens:
<style>
.left, .right {
float: left;
width: 20%; /* The width is 20%, by default */
}
float: left;
width: 60%; /* The width is 60%, by default */
}/* Use a media query to add a breakpoint at 800px: */
@media screen and (max-width: 800px) {
.left, .main, .right {
width: 100%; /* The width is 100%, when the viewport is 800px
or smaller */
}
}
</style>
Responsive Web Page - Full Example
A responsive web page should look good on large desktop screens and on small
mobile phones.Responsive Web Design - Frameworks
All popular CSS Frameworks offer responsive design.They are free, and easy to use.
London is the capital city of England.
over 13 million inhabitants.
Paris is the capital of France.
12 million inhabitants.
Tokyo is the capital of Japan.
area in the world.
<!DOCTYPE html>
<html>
<head>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.c
ss">
</head>
<body><div class="w3-container w3-green">
<h1>W3Schools Demo</h1>
<p>Resize this responsive page!</p>
</div>
<div class="w3-third">
<h2>London</h2>
<p>London is the capital city of England.</p>
<p>It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
</div>
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
<p>The Paris area is one of the largest population centers in
Europe,
with more than 12 million inhabitants.</p>
</div>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
<p>It is the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</div>
</html>
Bootstrap
Another popular CSS framework is Bootstrap:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/
bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/
bootstrap.bundle.min.js"></script>
</head>
<body><div class="container-fluid p-5 bg-primary text-white text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div><div class="container mt-5">
<div class="row">
<div class="col-sm-4">
<h3>Column 1</h3>
<p>Lorem ipsum...</p>
</div>
<div class="col-sm-4">
<h3>Column 2</h3>
<p>Lorem ipsum...</p>
</div>
<div class="col-sm-4">
<h3>Column 3</h3>
<p>Lorem ipsum...</p>
</div>
</div>
</div>
HTML Semantic Elements
Semantic elements = elements with a meaning.What are Semantic Elements?
A semantic element clearly describes its meaning to both the browser and the
developer.
content.Examples of semantic elements: <form>, <table>, and <article> - Clearly defines
its content.Semantic Elements in HTML
Many web sites contain HTML code like: <div id="nav"> <div class="header">
<div id="footer"> to indicate navigation, header, and footer.
parts of a web page:
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
HTML <section> Element
The <section> element defines a section in a document.According to W3C's HTML documentation: "A section is a thematic grouping of
content, typically with a heading."Examples of where a <section> element can be used:
Introduction
News items
Contact information
contact information.
Two sections in a document:
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is an international
organization working on issues regarding the conservation, research
and restoration of the environment, formerly named the World
Wildlife Fund. WWF was founded in 1961.</p>
</section>
<section>
<h1>WWF's Panda symbol</h1>
<p>The Panda has become the symbol of WWF. The well-known panda
logo of WWF originated from a panda named Chi Chi that was
transferred from the Beijing Zoo to the London Zoo in the same year
of the establishment of WWF.</p>
</section>HTML <article> Element
The <article> element specifies independent, self-contained content.
it independently from the rest of the web site.Examples of where the <article> element can be used:
Blog posts
User comments
Product cards
Newspaper articles
Three articles with independent, self-contained content:
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google, released in
2008. Chrome is the world's most popular web browser today!</p>
</article>
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by
Mozilla. Firefox has been the second most popular web browser since
January, 2018.</p>
</article>
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft, released
in 2015. Microsoft Edge replaced Internet Explorer.</p>
</article>
Use CSS to style the <article> element:
<head>
<style>
.all-browsers {
margin: 0;
padding: 5px;
background-color: lightgray;
}.all-browsers > h1, .browser {
margin: 10px;
padding: 5px;
}
background: white;
}.browser > h2, p {
margin: 4px;
font-size: 90%;
}
</style>
</head>
<body>
<h1>Most Popular Browsers</h1>
<article class="browser">
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google, released
in 2008. Chrome is the world's most popular web browser today!</p>
</article>
<article class="browser">
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by
Mozilla. Firefox has been the second most popular web browser since
January, 2018.</p>
</article>
<article class="browser">
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft,
released in 2015. Microsoft Edge replaced Internet Explorer.</p>
</article>
</article>
</html>Nesting <article> in <section> or
Vice Versa?
The <article> element specifies independent, self-contained content.The <section> element defines section in a document.
cannot!So, you will find HTML pages with <section> elements
containing <article> elements, and <article> elements
containing <section> elements.HTML <header> Element
The <header> element represents a container for introductory content or a set of
navigational links.A <header> element typically contains:
one or more heading elements (<h1> - <h6>)
logo or icon
authorship information
Note: You can have several <header> elements in one HTML document.
However, <header> cannot be placed within a <footer>, <address> or
another <header> element.
A header for an <article>:
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's
natural environment,
and build a future in which humans live in harmony with
nature.</p>
</article>HTML <footer> Element
The <footer> element defines a footer for a document or section.A <footer> element typically contains:
copyright information
contact information
sitemap
back to top links
related documentsYou can have several <footer> elements in one document.
A footer section in a document:
<p>Author: Hege Refsnes</p>
<p><a href="mailto:hege@example.com">hege@example.com</a></p>
</footer>
HTML <nav> Element
The <nav> element defines a set of navigation links.
The <nav> element is intended only for major blocks of navigation links.
determine whether to omit the initial rendering of this content.
A set of navigation links:
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>HTML <aside> Element
The <aside> element defines some content aside from the content it is placed in
(like a sidebar).The <aside> content should be indirectly related to the surrounding content.
Display some content aside from the content it is placed in:
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<h4>Epcot Center</h4>
<p>Epcot is a theme park at Walt Disney World Resort featuring
exciting attractions, international pavilions, award-winning
fireworks and seasonal special events.</p>
</aside>
Use CSS to style the <aside> element:
<head>
<style>
aside {
width: 30%;
padding-left: 15px;
margin-left: 15px;
float: right;
font-style: italic;
background-color: lightgray;
}
</style>
</head>
<body>
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<p>The Epcot center is a theme park at Walt Disney World Resort
featuring exciting attractions, international pavilions, award-
winning fireworks and seasonal special events.</p>
</aside>
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
</html>
HTML <figure> and <figcaption>
Elements
The <figure> tag specifies self-contained content, like illustrations, diagrams,
photos, code listings, etc.The <figcaption> tag defines a caption for a <figure> element.
The <figcaption> element can be placed as the first or as the last child of
a <figure> element.The <img> element defines the actual image/illustration.
<figure>
<img src="pic_trulli.jpg" alt="Trulli">
<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>Why Semantic Elements?
According to the W3C: "A semantic Web allows data to be shared and reused
across applications, enterprises, and communities."Semantic Elements in HTML
Below is a list of some of the semantic elements in HTML. <article> Defines independent, self-contained content
<aside> Defines content aside from the page content<details> Defines additional details that the user can view or
hide<figcaption Defines a caption for a <figure> element
><figure> Specifies self-contained content, like illustrations,
diagrams, photos, code listings, etc.<footer> Defines a footer for a document or section
<header> Specifies a header for a document or section
<main> Specifies the main content of a document
<mark> Defines marked/highlighted text
<nav> Defines navigation links
<section> Defines a section in a document
<summary> Defines a visible heading for a <details> element <time> Defines a date/time
Symbols or letters that are not present on your keyboard can be added to
HTML using entities.HTML Symbol Entities
HTML entities were described in the previous chapter.Many mathematical, technical, and currency symbols, are not present on a
normal keyboard.
entity number (a decimal or a hexadecimal reference) for the symbol:
Display the euro sign:<p>I will display €</p>
<p>I will display €</p>
<p>I will display €</p>Will display as:
I will display €
I will display €
I will display €
Some Mathematical Symbols
Supported by HTML
Char Number Entity Description∀ ∀ ∀ For all
∂ ∂ ∂ Partial differential
∃ ∃ ∃ There exists
∅ ∅ ∅ Empty sets
∇ ∇ ∇ Nabla
∈ ∈ ∈ Element of
∉ ∉ ∉ Not an element of
∋ ∋ ∋ Contains as member ∏ ∏ ∏ N-ary product
∑ ∑ ∑ N-ary summation
Full Math Symbols Reference
Some Greek Letters Supported by
HTML
Char Number Entity Description Α Α Α GREEK ALPHA
Β Β Β GREEK BETA
Γ Γ Γ GREEK GAMMA
Δ Δ Δ GREEK DELTA Ε Ε Ε GREEK EPSILON
Ζ Ζ Ζ GREEK ZETA
Full Greek Reference
Some Other Entities Supported by
HTML
Char Number Entity Description © © © COPYRIGHT
® ® ® REGISTERED
€ € € EURO SIGN
™ ™ ™ TRADEMARK ← ← LEFT ARROW
← ↑ ↑ UP ARROW
↑ → → RIGHT ARROW
→ ↓ ↓ DOWN ARROW
↓ ♠ ♠ ♠ SPADE
♣ ♣ ♣ CLUB
♥ ♥ ♥ HEART
♦ ♦ ♦ DIAMOND
Full Currency Reference
Full Arrows Reference
Full Symbols ReferenceUsing Emojis in HTML
Emojis are characters from the UTF-8 character set: 😄 😍 💗
😁 😁Full HTML Emoji Reference
HTML Emojis Examples
🚀🚁🚂🚃🚄HTML Emoji Transport Symbols
HTML Emoji Office Symbols
HTML Emoji People Symbols
HTML Emoji Animals SymbolsWhat are Emojis?
Emojis look like images, or icons, but they are not.The HTML charset Attribute
To display an HTML page correctly, a web browser must know the character set
used in the page.This is specified in the <meta> tag:
If not specified, UTF-8 is the default character set in HTML.
Many UTF-8 characters cannot be typed on a keyboard, but they can always be
displayed using numbers (called entity numbers):
B is 66
C is 67
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<p>I will display A B C</p>
<p>I will display A B C</p>
</html>
The <meta charset="UTF-8"> element defines the character set.
start the entity number with &# and end it with ; (semicolon).
Emojis are also characters from the UTF-8 alphabet:
😍 is 128525
💗 is 128151
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body><h1>My First Emoji</h1>
</html>
any other character in HTML.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
😀 😄 😍 💗
</p>
</html>
HTML Forms
An HTML form is used to collect user input. The user input is most often sent
to a server for processing.
First name:
John
DoeThe <form> Element
The HTML <form> element is used to create an HTML form for user input:
.
form elements
.
</form>
text fields, checkboxes, radio buttons, submit buttons, etc.
Elements.The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on
the type attribute.Here are some examples:
<input type="text"> Displays a single-line text input field
<input type="radio"> Displays a radio button (for selecting one of
many choices) <input Displays a checkbox (for selecting zero or
type="checkbox"> more of many choices) <input Displays a submit button (for submitting the
type="submit"> form) <input Displays a clickable button
type="button">
The <input type="text"> defines a single-line input field for text input.
Example
A form with input fields for text:
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>This is how the HTML code above will be displayed in a browser:
field is 20 characters.The <label> Element
Notice the use of the <label> element in the example above.The <label> tag defines a label for many form elements.
reader will read out loud the label when the user focuses on the input element.
regions (such as radio buttons or checkboxes) - because when the user clicks
the text within the <label> element, it toggles the radio button/checkbox.
the <input> element to bind them together.
The <input type="radio"> defines a radio button.Radio buttons let a user select ONE of a limited number of choices.
A form with radio buttons:<p>Choose your favorite Web language:</p>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="Ja
vaScript">
<label for="javascript">JavaScript</label>
</form>This is how the HTML code above will be displayed in a browser:
Choose your favorite Web language:
CSS
JavaScript
The <input type="checkbox"> defines a checkbox.Checkboxes let a user select ZERO or MORE options of a limited number of
choices.
A form with checkboxes:
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike"
>
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat"
>
<label for="vehicle3"> I have a boat</label>
</form>This is how the HTML code above will be displayed in a browser:
I have a car
I have a boatThe Submit Button
The <input type="submit"> defines a button for submitting the form data to a
form-handler.
input data.The form-handler is specified in the form's action attribute.
A form with a submit button:
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>This is how the HTML code above will be displayed in a browser:
First name:
John
DoeThe Name Attribute for <input>
Notice that each input field must have a name attribute to be submitted.
This example will not submit the value of the "First name" input field:
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>HTML Form Attributes
This chapter describes the different attributes for the HTML <form> element.The Action Attribute
The action attribute defines the action to be performed when the form is
submitted.
submit button.
In the example below, the form data is sent to a file called "action_page.php".
This file contains a server-side script that handles the form data:
On submit, send form data to "action_page.php":
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>The Target Attribute
The target attribute specifies where to display the response that is received
after submitting the form.The target attribute can have one of the following values:
_blank The response is displayed in a new window or tab
_self The response is displayed in the current window
_parent The response is displayed in the parent frame
_top The response is displayed in the full body of the window framenam The response is displayed in a named iframe
e
current window.
Here, the submitted result will open in a new browser tab:<form action="/action_page.php" target="_blank">
The Method Attribute
The method attribute specifies the HTTP method to be used when submitting the
form data.The form-data can be sent as URL variables (with method="get") or as HTTP
post transaction (with method="post").The default HTTP method when submitting form data is GET.
This example uses the GET method when submitting the form data:<form action="/action_page.php" method="get">
This example uses the POST method when submitting the form data:<form action="/action_page.php" method="post">
Appends the form data to the URL, in name/value pairs
NEVER use GET to send sensitive data! (the submitted form data is visible
in the URL!)
The length of a URL is limited (2048 characters)
Useful for form submissions where a user wants to bookmark the result
GET is good for non-secure data, like query strings in Google
submitted form data is not shown in the URL)
POST has no size limitations, and can be used to send large amounts of
data.
Form submissions with POST cannot be bookmarked
information!The Autocomplete Attribute
The autocomplete attribute specifies whether a form should have
autocomplete on or off.When autocomplete is on, the browser automatically complete values based on
values that the user has entered before.
A form with autocomplete on:<form action="/action_page.php" autocomplete="on">
The Novalidate Attribute
The novalidate attribute is a boolean attribute.
when submitted.
Example
A form with a novalidate attribute:<form action="/action_page.php" novalidate>
List of All <form> Attributes
Attribute Description accept- Specifies the character encodings used for form submission
charset action Specifies where to send the form-data when a form is submitted
autocomplete Specifies whether a form should have autocomplete on or off
server (only for method="post") method Specifies the HTTP method to use when sending form-data
name Specifies the name of the form
rel Specifies the relationship between a linked resource and the current
document
the formHTML Canvas Graphics
The HTML <canvas> element is used to draw graphics on a web page.
red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor
text.What is HTML Canvas?
The HTML <canvas> element is used to
draw graphics, on the fly, via JavaScript. The <canvas> element is only a container
for graphics. You must use JavaScript to
actually draw the graphics. Canvas has several methods for drawing
paths, boxes, circles, text, and adding
images.Canvas is supported by all major browsers.
A canvas is a rectangular area on an HTML page. By default, a canvas has no
border and no content.
The markup looks like this:<canvas id="myCanvas" width="200" height="100"></canvas>
Note: Always specify an id attribute (to be referred to in a script), and
a width and height attribute to define the size of the canvas. To add a border,
use the style attribute.Here is an example of a basic, empty canvas:
<canvas id="myCanvas" width="200" height="100" style="border:1px
solid #000000;">
</canvas>
After creating the rectangular canvas area, you must add a JavaScript to do the
drawing.Here are some examples:
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
</script>
Stroke Text
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
</script>Draw Linear Gradient
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
</script>
Draw Circular Gradient
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
</script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
</script>
HTML SVG Graphics
SVG (Scalable Vector Graphics)
which can be directly embedded in HTML pages.
resized:SVG is supported by all major browsers.
SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines graphics in XML format
Each element and attribute in SVG files can be animated
SVG is a W3C recommendation
SVG integrates with other standards, such as CSS, DOM, XSL and
JavaScriptThe <svg> Element
The HTML <svg> element is a container for SVG graphics.
and much more.
Example
<!DOCTYPE html>
<html>
<body><svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fi
ll="yellow" />
</svg>
</html>
Example
<svg width="400" height="120">
<rect x="10" y="10" width="200" height="100" stroke="red" stroke-
width="6" fill="blue" />
</svg>SVG Rectangle with Opacity and
Rounded Corners
Example
<svg width="400" height="180">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>
Example
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-
rule:evenodd;" />
</svg>SVG Gradient Ellipse and Text
SVG
<svg height="130" width="500">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="yellow" />
<stop offset="100%" stop-color="red" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="50"
y="86">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>Differences Between SVG and Canvas
SVG is a language for describing 2D graphics in XML, while Canvas draws 2D
graphics, on the fly (with JavaScript).
DOM. You can attach JavaScript event handlers to SVG graphics.In SVG, each drawn shape is remembered as an object. If attributes of an SVG
object are changed, the browser can automatically re-render the shape.Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is
forgotten by the browser. If its position should be changed, the entire scene
needs to be redrawn, including any objects that might have been covered by the
graphic.
Comparison of SVG and Canvas
The table below shows some important differences between Canvas and SVG: Resolution independent Resolution dependent
Support for event handlers No support for event handlers
Good text rendering Poor text rendering capabilities
capabilities You can save the resulting image as .png
Slow rendering if complex or .jpg
Not suited for game Well suited for graphic-intensive games
applications
Multimedia on the web is sound, music, videos, movies, and animations.
Multimedia comes in many different formats. It can be almost anything you can
hear or see, like images, music, sound, videos, records, films, animations, and
more.
The first web browsers had support for text only, limited to a single font in a
single color.
Later came browsers with support for colors, fonts, images, and multimedia!
Multimedia elements (like audio or video) are stored in media files.
extension.Multimedia files have formats and different extensions
like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.Common Video Formats
There are many video formats out there. The MP4, WebM, and Ogg formats are supported
by HTML. The MP4 format is recommended by YouTube.
Format File Description
.mpeg 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. QuickTim .mov QuickTime. Developed by Apple. Commonly used in video
e cameras and TV hardware. Plays well on Apple computers, but
not in web browsers. RealVideo .rm RealVideo. Developed by Real Media to allow video streaming
.ram with low bandwidths. Does not play in web browsers. Flash .swf Flash. Developed by Macromedia. Often requires an extra
.flv 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 .mp4 MP4. Developed by the Moving Pictures Expert Group.
or MP4 Commonly used in video cameras and TV hardware. Supported
by all browsers and recommended by YouTube.
Common Audio Formats
MP3 is the best format for compressed recorded music. The term MP3 has
become synonymous with digital music.If your website is about recorded music, MP3 is the choice.
Format File Description
.midi 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. RealAudi .rm RealAudio. Developed by Real Media to allow streaming of audio
o .ram with low bandwidths. Does not play in web browsers.
on Windows computers, but not in web browsers. AAC .aac AAC (Advanced Audio Coding). Developed by Apple as the
default format for iTunes. Plays well on Apple computers, but
not in web browsers.
Macintosh, and Linux operating systems. Supported by HTML. Ogg .ogg Ogg. Developed by the Xiph.Org Foundation. Supported by
HTML.
most popular format for music players. Combines good
compression (small files) with high quality. Supported by all
browsers.
by all browsers.
The HTML <video> element is used to show a video on a web page.
Courtesy of Big Buck Bunny:The HTML <video> Element
To show a video in HTML, use the <video> element:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
How it Works
The controls attribute adds video controls, like play, pause, and volume.
width are not set, the page might flicker while the video loads.
browser may choose from. The browser will use the first recognized format.
browsers that do not support the <video> element.HTML <video> Autoplay
To start a video automatically, use the autoplay attribute:
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>Note: Chromium browsers do not allow autoplay in most cases. However,
muted autoplay is always allowed.
muted):
<video width="320" height="240" autoplay muted>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Browser Support
The numbers in the table specify the first browser version that fully supports
the <video> element. <video> 4.0 9.0 3.5 4.0 10.5
HTML Video Formats
There are three supported video formats: MP4, WebM, and Ogg. The browser
support for the different formats is: Browser MP4 WebM Ogg
Edge YES YES YES
Chrome YES YES YES
Firefox YES YES YES
Safari YES YES NO
Opera YES YES YESHTML Video - Media Types
File Format Media TypeHTML Video - Methods, Properties, and
Events
The HTML DOM defines methods, properties, and events for
the <video> element.
volume.
paused, etc.Example: Using JavaScript
Play/Pause Big Small Normal Video courtesy of Big Buck Bunny.
HTML Video Tags
Tag Description <video> Defines a video or movie
<source> Defines multiple media resources for media elements, such as
<video> and <audio> <track> Defines text tracks in media players
The HTML <audio> element is used to play an audio file on a web page.The HTML <audio> Element
To play an audio file in HTML, use the <audio> element:
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>HTML Audio - How It Works
The controls attribute adds audio controls, like play, pause, and volume.
browser may choose from. The browser will use the first recognized format.
browsers that do not support the <audio> element.HTML <audio> Autoplay
To start an audio file automatically, use the autoplay attribute:
<audio controls autoplay>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>Note: Chromium browsers do not allow autoplay in most cases. However,
muted autoplay is always allowed.
muted):
<audio controls autoplay muted>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
The numbers in the table specify the first browser version that fully supports
the <audio> element. <audio> 4.0 9.0 3.5 4.0 10.5
HTML Audio Formats
There are three supported audio formats: MP3, WAV, and OGG. The browser
support for the different formats is: Browser MP3 WAV OGG
Edge/IE YES YES* YES*
Chrome YES YES YES
Firefox YES YES YES
Safari YES YES NO Opera YES YES YES
HTML Audio - Media Types
File Format Media TypeHTML Audio - Methods, Properties, and
Events
The HTML DOM defines methods, properties, and events for
the <audio> element.
volume.
There are also DOM events that can notify you when an audio begins to play, is
paused, etc.HTML Audio Tags
Tag Description <audio> Defines sound content
<source> Defines multiple media resources for media elements, such as
<video> and <audio>
Plug-ins are computer programs that extend the standard functionality of the
browser.
Plug-ins were designed to be used for many different purposes: To run Java applets
To run Microsoft ActiveX controls
To display Flash movies
To display maps
To scan for viruses
To verify a bank id
Most browsers no longer support Java Applets and Plug-ins.ActiveX controls are no longer supported in any browsers.
The <object> Element
The <object> element is supported by all browsers.The <object> element defines an embedded object within an HTML document.
Players) in web pages, but can also be used to include HTML in HTML:
<object width="100%" height="500px" data="snippet.html"></object>Or images if you like:
<object data="audi.jpeg"></object>The <embed> Element
The <embed> element is supported in all major browsers.The <embed> element also defines an embedded object within an HTML
document.
it has not been a part of the HTML specification before HTML5.
<embed src="audi.jpeg">
Note that the <embed> element does not have a closing tag. It can not contain
alternative text.The <embed> element can also be used to include HTML in HTML:
<embed width="100%" height="500px" src="snippet.html">HTML YouTube Videos
The easiest way to play videos in HTML, is to use YouTube.Struggling with Video Formats?
Converting videos to different formats can be difficult and time-consuming.
YouTube will display an id (like tgbNymZ7vqY), when you save (or play) a video.Playing a YouTube Video in HTML
To play your video on a web page, do the following: Upload the video to YouTube
Take a note of the video id
Define an <iframe> element in your web page
Let the src attribute point to the video URL
Use the width and height attributes to specify the dimension of the
player
Add any other parameters to the URL (see below)
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>YouTube Autoplay + Mute
You can let your video start playing automatically when a user visits the page,
by adding autoplay=1 to the YouTube URL. However, automatically starting a
video is annoying for your visitors!Note: Chromium browsers do not allow autoplay in most cases. However,
muted autoplay is always allowed.
muted).YouTube - Autoplay + Muted
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1&mute=1">
</iframe>
A comma separated list of videos to play (in addition to the original URL).
Add loop=1 to let your video loop forever.
Value 0 (default): The video will play only once.Value 1: The video will loop (forever).
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY?
playlist=tgbNymZ7vqY&loop=1">
</iframe>
Add controls=0 to not display controls in the video player.Value 0: Player controls does not display.
Value 1 (default): Player controls display.
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY?controls=0">
</iframe>HTML Geolocation API
The HTML Geolocation API is used to locate a user's position.Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a user.
approves it.
Note: Geolocation is most accurate for devices with GPS, like smartphones.
The numbers in the table specify the first browser version that fully supports
Geolocation. Geolocation 5.0 - 49.0 (http) 9.0 3.5 5.0 16.0
50.0 (https)
such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the
requests to get the users location will no longer function.Using HTML Geolocation
The getCurrentPosition() method is used to return the user's position.
<script>
const x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script> 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 LongitudeHandling 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
This page has demonstrated how to show a user's position on a map.Geolocation is also very useful for location-specific information, like:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)The getCurrentPosition() Method -
Return Data
The getCurrentPosition() method returns an object on success. The latitude,
longitude and accuracy properties are always returned. The other properties are
returned if available: 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)
if available)
coords.altitudeAccurac The altitude accuracy of position (returned if available)
y 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.
GPS device to test this (like smartphone):
<script>
const x = document.getElementById("demo");
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 and Drop API
In HTML, any element can be dragged and dropped.Drag the W3Schools image into the rectangle.
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and
drag it to a different location.
The numbers in the table specify the first browser version that fully supports
Drag and Drop. Drag and Drop 4.0 9.0 3.5 6.0 12.0
HTML Drag and Drop Example
The example below is a simple drag and drop example:
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
ev.dataTransfer.setData("text", ev.target.id);
}
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body><div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"><
/div><img id="drag1" src="img_logo.gif" draggable="true" ondragstart="dr
ag(event)" width="336" height="69">
</html>
and drop event.
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to true:What to Drag - ondragstart and
setData()
Then, specify what should happen when the element is dragged.In the example above, the ondragstart attribute calls a function, drag(event),
that specifies what data to be dragged.
dragged data:
ev.dataTransfer.setData("text", ev.target.id);
}
element ("drag1").Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.By default, data/elements cannot be dropped in other elements. To allow a drop,
we must prevent the default handling of the element.This is done by calling the event.preventDefault() method for the ondragover
event:
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.In the example above, the ondrop attribute calls a function, drop(event):
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
} Call preventDefault() to prevent the browser default handling of the data
(default is open as link on drop)
Get the dragged data with the dataTransfer.getData() method. This
method will return any data that was set to the same type in the setData()
method
The dragged data is the id of the dragged element ("drag1")
Append the dragged element into the drop elementHTML Web Storage API
HTML web storage; better than cookies.What is HTML Web Storage?
With web storage, web applications can store data locally within the user's
browser.Before HTML5, application data had to be stored in cookies, included in every
server request. Web storage is more secure, and large amounts of data can be
stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is
never transferred to the server.
can store and access the same data.
The numbers in the table specify the first browser version that fully supports
Web Storage. Web Storage 4.0 8.0 3.5 4.0 11.5
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)
sessionStorage:if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not
be deleted when the browser is closed, and will be available the next day, week,
or year.
// Store
localStorage.setItem("lastname", "Smith");
document.getElementById("result").innerHTML =
localStorage.getItem("lastname"); Create a localStorage name/value pair with name="lastname" and
value="Smith"
Retrieve the value of "lastname" and insert it into the element with
id="result"The example above could also be written like this:
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML =
localStorage.lastname;The syntax for removing the "lastname" localStorage item is as follows:
Note: Name/value pairs are always stored as strings. Remember to convert
them to another format when needed!
In this code the value string is converted to a number to be able to increase the
counter:
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the
button " +
localStorage.clickcount + " time(s).";The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it
stores the data for only one session. The data is deleted when the user closes
the specific browser tab.
in the current session:
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)
+ 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the
button " +
sessionStorage.clickcount + " time(s) in this session.";HTML Web Workers API
A web worker is a JavaScript running in the background, without affecting the
performance of the page.What is a Web Worker?
When executing scripts in an HTML page, the page becomes unresponsive until
the script is finished.
A web worker is a JavaScript that runs in the background, independently of other
scripts, without affecting the performance of the page. You can continue to do
whatever you want: clicking, selecting things, etc., while the web worker runs in
the background.
The numbers in the table specify the first browser version that fully support Web
Workers. Web Workers 4.0 10.0 3.5 4.0 11.5
HTML Web Workers Example
The example below creates a simple web worker that count numbers in the
background:
Count numbers:Start Worker Stop Worker
Check Web Worker Support
Before creating a web worker, check whether the user's browser supports it:if (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}Create a Web Worker File
Now, let's create our web worker in an external JavaScript.Here, we create a script that counts. The script is stored in the
"demo_workers.js" file:
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
used to post a message back to the HTML page.
CPU intensive tasks.Create a Web Worker Object
Now that we have the web worker file, we need to call it from an HTML page.
web worker object and runs the code in "demo_workers.js":
w = new Worker("demo_workers.js");
}
Then we can send and receive messages from the web worker.Add an "onmessage" event listener to the web worker.
document.getElementById("result").innerHTML = event.data;
};
executed. The data from the web worker is stored in event.data.Terminate a Web Worker
When a web worker object is created, it will continue to listen for messages
(even after the external script is finished) until it is terminated.To terminate a web worker, and free browser/computer resources, use
the terminate() method:Reuse the Web Worker
If you set the worker variable to undefined, after it has been terminated, you
can reuse the code:Full Web Worker Example Code
We have already seen the Worker code in the .js file. Below is the code for the
HTML page:
<!DOCTYPE html>
<html>
<body><p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
var w;
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web
Worker support.";
}
}
w.terminate();
w = undefined;
}
</script>
</html>Web Workers and the DOM
Since web workers are in external files, they do not have access to the following
JavaScript objects: The window object
The document object
The parent object
HTML SSE API
Server-Sent Events (SSE) allow a web page to get updates from a server.Server-Sent Events - One Way
Messaging
A server-sent event is when a web page automatically gets updates from a
server.
updates were available. With server-sent events, the updates come
automatically.Examples: Facebook/Twitter updates, stock price updates, news feeds, sport
results, etc.
The numbers in the table specify the first browser version that fully support
server-sent events. SSE 6.0 79.0 6.0 5.0 11.5
Receive Server-Sent Event
Notifications
The EventSource object is used to receive server-sent event notifications:
Example
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>
";
};
sending the updates (in this example "demo_sse.php")
Each time an update is received, the onmessage event occurs
When an onmessage event occurs, put the received data into the element
with id="result"Check Server-Sent Events Support
In the tryit example above there were some extra lines of code to check browser
support for server-sent events:if(typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
} else {
// Sorry! No server-sent events support..
}Server-Side Code Example
For the example above to work, you need a server capable of sending data
updates (like PHP or ASP).
"text/event-stream". Now you can start sending event streams.Code in PHP (demo_sse.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo "data: The server time is: {$time}\n\n";
flush();
?>Code in ASP (VB) (demo_sse.asp):
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%> Set the "Content-Type" header to "text/event-stream"
Specify that the page should not cache
Output the data to send (Always start with "data: ")
Flush the output data back to the web pageThe EventSource Object
In the examples above we used the onmessage event to get messages. But
other events are also available: onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occursYou might also like