upGrad KnowledgeHut SkillFest Sale!

HTML Interview Questions and Answers

Hypertext Markup Language (HTML) is a standard markup language used to create and design web pages. HTML uses tags to mark up elements such as headings, paragraphs, images, links, and other content that appears on a web page. With HTML, web designers and developers can create web pages that are accessible, interactive, and visually appealing. Whether you are a beginner or preparing for an advanced-level developer interview, our set of HTML interview questions and the detailed answers will help you prepare for the interview more confidently.

  • 4.5 Rating
  • 60 Question(s)
  • 30 Mins of Read
  • 853 Reader(s)

Advanced

HTML5 has been developed considering current and future browser development and past, present, and future web development work. Due to this, HTML5 gained significant momentum. Driven by practicality, it has emerged as the W3C’s choice for accelerated development.

HTML5 is backward compatible and it contains all the features of the HTML4 spec, though with a few changes and improvements. It also contains additional capabilities for building dynamic web applications and creating higher quality markup.

Features of HTML5

  • New Semantic elements to allow us to define more parts of our markup unambiguously and semantically rather than using lots of classes and IDs.
  • APIs for adding video, audio, scriptable graphics, and other rich application type content to our sites.
  • HTML5 has been deliberately built to compete with proprietary plug-ins such as Flash and Silverlight.
  • New features for standardizing functionality that we already built in bespoke, hacky ways. Server-sent updates and form validation spring to mind immediately.
  • Microdata: Microdata allows machine-readable data to be embedded in HTML documents so that browsers and search engines can extract data from the page.  
  • Web Workers: Allows a JavaScript operation to work in the background without interfering with the user’s browsing.
  • Web Storage: This is a more powerful form of a cookie. It can store a large amount of data on the client side. It can store up to 5MB of data, whereas a cookie is limited to about 4KB.
  • Web Sockets: Allows pages to use the WebSocket protocol to send two-way messages between a browser and a server.
  • Cross-document and channel messaging: Cross-document messaging provides a capability to exchange documents regardless of the source domain and without enabling cross-site attacks. Channel messaging uses independent pieces of code blocks to communicate directly.
  • Server sent events: Using this feature, push notifications can be sent from a server to a client browser as DOM events.
  • New features to plug gaps in the functionality we traditionally had available in open standards, such as defining how browsers should handle markup errors, allowing web apps to work offline, allowing us to use always-open socket connections for app data transfer, and again, audio, video and scriptable images (canvas).

Expect to come across this popular question in HTML interview questions and answers.

HTML5 introduces more than a dozen new input types for forms. The new input types provide dual benefits

  • Less development time
  • Improved user experience.   

Below are the new input types and it’s usage.

  • Search: Search is the most common action perform on the web every day. Search is not only for Google, Bing, or Yahoo, but it can be a field on e-commerce site we make a purchase from on the web, on Wikipedia, and even on a personal blog. The syntax for Search is
<input type="search" name="search">
  • Email:  Email input type is no different from a standard text input type but it allows one or more e-mail addresses to be entered with the required attribute. The browser looks for patterns to ensure a valid e-mail address has been entered. The syntax for Email is
<input type="email" name="email" required>

The URL input type is for web addresses.  The browser will carry out simple validation and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces and possibly detecting a valid top-level domain (such as .com or .co.uk).  It also supports multiple addresses. The syntax for Url is

<input type="url" name="url" required>
  • Tel: tel does not have any particular syntax enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered.  Validation against specific phone number format can be done using client-side validation. The syntax for tel is
<input type="tel" name="tel" id="tel" required>
  • Number: Number is used for specifying a numerical value. It, Safari, and Chrome, number input is rendered as a spinbox control whereby the user can click the arrows to move up or down or enter directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type="number" will be in IE 10 also.  With the additional attributes min, max, and step, we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). The syntax for number is
<input type="number" min="5" max="18" step="0.5" value="9" name="shoe-size" >
  • Range: The Range input type is similar to number but more specific. It represents a numerical value within a given range. In Opera, Safari, and Chrome, type="range" renders as a slider. The syntax for range is
<input id="skill" type="range" min="1" max="100" value="0">
  • Date: HTML5 provides date control which provides a date picker functionality with is integrated with the browser without any external libraries.  Date control allows to select a single date; select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward. The syntax for Date is
<input id="dob" name="dob" type="date">

Also, using the min and max attributes to ensure the user can only choose from a specified date range.

<input id="startdate" name="startdate" min="2012-01-01" max="2013-01-01" type="date"> 
  • Month: Month is used to select a particular month on the web page. It can be used for a credit card expiry date. The syntax for month is
<input id="expiry" name="expiry" type="month" required>
  • Week: week is used to select a particular week in a month. The syntax for week is
<input id="vacation" name="vacation" type="week">
  • time : time renders a spinbox for selecting the precise time. The syntax for time is
<input id="exit-time" name="exit-time" type="time">
  • DateTime: We can combine the date and time by using type="datetime" for specifying a precise time on a given day. The syntax for datetime is
<input id="entry-day-time" name="entry-day-time" type="datetime">
  • Datetime-local: Using datetime-local, user can select a precise time on a given day with a local time zone variation. The syntax for datetime-local is
<input id="arrival-time" name="arrival-time " type="datetime-local">
  • Color: The Color input type allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker,. The syntax for color is
<input id="color" name="color" type="color"> 

Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. You should always use the latest version. To use it, include the following highlighted <script> element at the top of your page.

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Dive Into HTML5</title>
  <script src="modernizr.min.js"></script>
</head>
<body></body>
</html>

Following are the Apis supported by Modernizr

  • Modernizr.canvas attribute is used to detect support for the canvas API. 
  • Modernizr.canvastext attribute is used to detect support for the canvas text API.
  • Modernizr.video attribute is used to detect support for HTML5 video. 
  • Modernizr.localstorage attribute is used to detect support for HTML5 local storage. 
  • Modernizr.webworkers attribute is used to detect support for web workers.
  • Modernizr.applicationcache is used to detect support for offline web applications.
  • Modernizr.geolocation is used to detect support for the geolocation API.

The Web is based on hyperlinks. Each Web page contains active links to other pages, which in turn link to even more pages, until presumably the entire Web (or at least a great chunk of it) is bound together. In fact, that’s where the name “web” comes from. Hyperlinks can connect to other places on a Web page, to other pages within the Web site, to pages outside the site, and to many types of Web and non-Web content.

  • Scenario 1: Hyperlinking to a Web Page.

The syntax for a hyperlink starts with <a> tag and uses an href=attribute which provides the URL or path to a destination.

E.g <a href="http://www.microsoft.com">

This is followed by the text that will appear underlined as the link text that user click, or by a reference to the image that will serve as a hyperlink

E.g Visit <a href="http://www.microsoft.com">Microsoft.com</a> for the latest information.
  • Scenario 2: Using Partial Paths and Filenames

In order to link to a specific page, the complete file name should be specified. Example, To provide a direct link to the page where users can download Windows Media Player, it should have the following tag:

<a href="http://www.microsoft.com/windows/windowsmedia/player/download/download.aspx">Download Windows Media Player</a>
  • Scenario 3: Using Relative and Absolute Paths

Paths that contain a complete address that anyone can use to get to that page are called absolute paths. Absolute paths are very reliable, but they are also long and awkward to type.

E.g <a href="http://www.microsoft.com/articles/Windows10.htm">Windows 10</a>

Instead of providing the full path only the destination file is provided, it is called a relative path. Below are the relative path examples.

<a href=" Windows10.htm">Windows 10</a>
<a href=“articles/ Windows10.htm">Windows 10</a>
  • Scenario 4: Setting a Target Window

To direct the hyperlink to open a page in a new window, add the attribute target=″_blank″ to the <a> tag. For example, to open the foliage.htm file in a new window, the tag would be structured like this:

<a href=" Windows10.htm " target="_blank">Windows10</a>
  • Scenario 5: Hyperlinking to an E-Mail Address

Hyperlinks can point not only to web pages but also to email address. Email hyperlinks are useful to send a message to a particular person directly.

<a href="mailto:support@microsoft.com">Contact Us</a>
  • Scenario 6: Creating and Hyperlinking to Anchors

An anchor is a marker within an HTML document, roughly analogous to a bookmark in a Word document. Define a specific location in the document with an anchor name, and then hyperlink directly to that anchor. Anchors are most valuable in long documents with multiple sections. They provide a means for users to jump directly to whatever section they want rather than having to read or scroll through the entire document.  

E.g

<div id="top">conclusion </div>
    <a href="#conclusion">View the Conclusion</a> # plays a critical for identifying the section

<section> is best used as a sub-section of an <article> and should always contain and enclose a heading, something like the following:

  • Don’t use <section> as a target for styling or scripting; use a <div> for that
  • Don’t use <section> if <article>, <aside>, or <nav> is more appropriate.
  • Don’t use <section> unless there is naturally a heading at the start of the section.
<article>
<h1>A heading, any level from h1 to h6</h1>
<section>  
<h1>A heading, any level from h1 to h6</h1>some content
</section>
<section>
<h1>A heading, any level from h1 to h6</h1>some content
</section>
 </article> 

An <article> is a stand-alone item, such as a self-contained piece of information that could be lifted from the page and published in a forum, magazine, RSS feed, or newspaper. It should contain and enclose a heading (h1 to h6) and it can contain two or more sections. The key words are STAND ALONE.

This is a frequently asked question in HTML interview questions for freshers.

While grouping headings resulted in problems with the outline of a document; this problem is called phantom nodes.  To avoid the phantom nodes, use <hgroup> to group two or more headings (h1, h2, h3 ,h4, h5, and h6).

<hgroup></hgroup> is a container for two or more headings (h1, h2, h3 ,h4, h5, and h6). It indicates that the headings are closely related, so it will be used to group together headings with subheadings, titles, and subtitles.  Using <hgroup> avoids phantom nodes problem because it combines the two headings into one node. The <hgroup> tags can only contain headings.

The following is an example:

Example

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Images</title>
    <style type="text/css">
       h1 { font-size:160%; font-weight:bold; margin-top:5px; margin-bottom:0; }
       h2 { font-size:130%; font-weight:bold; margin-top:0; margin-bottom:5px; }
       article { width:445px; text-align:left;  }
    </head>
    <body>
         <article> <hgroup> <h1>I put our holiday dates and address on a social network</h1>
               <h2>An idiot's tale</h2>  </hgroup> <p>We returned to a ransacked house, even the furniture was taken.<br> Your friend, <br>Sreekanth</p>
          </article>
    <body>
</html>

Outputphantom nodes

Rewrite the following code to apply the caption “This is an image of something interesting’

<img src="path/to/image" alt="About image" />
<p>Image of Mars. </p>

There is no easy or semantic way to associate the caption, wrapped in a paragraph tag, with the image element itself.  Using HTML5 <figure> element along with <figcaption> element, we can now semantically associate captions with their image counterparts.

Example

<figure>
   <img src="path/to/image" alt="About image" />
   <figcaption>
       <p>This is an image of something interesting. </p>
   </figcaption>
</figure>

Output

Caching generally refers to the storage of web resources (HTML documents, images, and so on) in a temporary location to improve performance. Caches can be implemented by most web browsers, perimeter (intermediate) web proxies, and at the gateways of large internal networks. Transparent proxies (caches) are used by many Internet Service Providers (ISPs), reverse proxies sit in front of web servers, and the web server itself utilizes caching.

Different types of caching are explained below.

  • Caching by Browsers

Web browsers implement a cache to hold recently and frequently accessed resources. It is much faster to retrieve a resource from the cache than to request it again from the web server. When deciding what to cache, browsers are usually quite well behaved and respect the caching policy dictated by the server.

There are several problems with browser caching. The size of the cache tends to be quite small by default and when the cache becomes full, the algorithm to decide what to remove is crude. Commonly, the Least Recently Used (LRU) algorithm is used to purge old items.

  • Intermediate Caches:

The intermediate cache/proxy is commonly used by ISPs and larger organizations. When used by ISPs, it typically takes the form of a transparent caching proxy that silently intercepts HTTP traffic. When the client makes a request, the proxy intercepts it and checks its local cache for a copy of the resource. If none is found, it makes the request on the client’s behalf and then relays this back to the client, caching a copy itself in the process. When another client on the same ISP requests the same resource, a cached copy is returned.

Reverse Proxies Browser caches and intermediate proxies are generally for the benefit of the client, reverse proxies are usually used for the benefit of the web server. These proxies sit in front of the web server and have two purposes (although sometimes they are used for just one of these reasons): caching and load balancing. For caching, they can be used to lighten the load on the back-end web server by serving up cached versions of dynamically generated pages (thus cutting CPU usage). For load balancing, they can be used for load-balancing multiple back-end web servers.

Below are the different ways to control the cache.

  • Controlling Caching
  • Conditional GETs: Send a conditional GET request, the request knows if a local, cached copy of a resource is still valid.  The “If-Modified-Since header” is sent in the request. If the server determines that the resource has been modified since the date given in this header, the resource is returned as normal. Otherwise, a 304 Not Modified status is returned.
  • Utilizing Cache-Control and Expires Headers: Apart from “If-Modified-Since header”, there are two more headers that can control caching: Expires and Cache-Control: max-age. These headers effectively say to the client, “This resource expires on such-and-such a date. Until then, use your locally cached copy (if you have one).” The result is that the client doesn’t need to issue a conditional GET.
    • ExpiresByType image/gif "access plus 2 months“
    • ExpiresByType image/jpeg "access plus 2 months“

Minification is the act to strip out unnecessary characters from code to reduce the size, and a minifier is the tool that does it. Most often, the term is applied to JavaScript, but as you shall see, the technique can also be used on JavaScript, CSS and HTML.

JavaScript Minification: JavaScript offers the most potential for minification. Aside from removing white spaces and comments, Windows-style line breaks (CRLF) can be converted to UNIX-style breaks (LF), and variable names can be shortened.

function toggle(elementID) {   
     if ( document.getElementById(elementID).style.display != 'none’ ) {  
        document.getElementById(elementID).style.display  = 'none';
     } else {  
         document.getElementById(elementID).style.display = '';  
    }}
function toggle(elementID) {
   var el = document.getElementById(elementID);   
   if ( el.style.display != 'none' ) {       
        el.style.display = 'none’;
    } else {     
   el.style.display = '';
}}

CSS Minification : Many of the minification techniques outlined for JavaScript minification are also applicable to CSS — the removal of extra whitespaces, removal of comments, and conversion of CRLF to LF.

.myclass {    
           margin-left: 10px;  
            margin-right: 10px;
           margin-bottom: 20px;
           margin-top: 20px;}
myclass { margin: 20px 10px;}

Html Minification: Html minification is newer and is still experimental. Following are the available options:

  • Remove comments.
  • Remove comments from JavaScript and CSS blocks.
  • Remove character data (CDATA) blocks from CSS and JavaScript.
  • Collapse whitespace.
  • Collapse boolean attributes (for example, selected="selected").
  • Remove attribute quotes (when it is safe to do so).
  • Remove redundant attributes (for example, language="JavaScript").
  • Use short doctype.
  • Remove empty attributes (for example, title="").
  • Remove optional closing tags.
  • Remove empty elements such as <p></p>.
  • Remove type="text/javascript" from inline script.

OPTIMIZING IMAGES: Implementing compression on an image with our impacting the quality can reduce the size of the image.  There are different ways to improve the performance of a web page when images are present.

  • Reduce the Image size
  • Eliminating the Http request for favicon instead use Data URI
  • Use Lazy loading
  • Avoid empty src attributes
  • Setting appropriate width and height attributes

It's no surprise that this one pops up often in HTML interview questions and answers for freshers.

HTML5 introduced different approaches for web developers to save persistent content on a user’s machine namely Local Storage, aka Web Storage and WebSQL Storage. Local Storage feature is easy and here is the syntax for storing and retrieving.

<script>
localStorage.setItem(“Name”, “Sreekanth”);
var firstName = localStorage.getItem(“Name”);
</script>

Information is stored as key-value pair and can be easily stored and retrieved using a simple API. Event handlers can also be registered to monitor for changes to localStorage values.  localStorage is well supported in modern browsers and it is consistently supported across desktop and mobile browsers.

The localStorage object provides much more space than was available with older tools. Modern browsers support a minimum of 5 MB of data, which is substantially more than is allowed through cookies (which are limited to 4 KB each).

If the storage limit is reached, or if the user manually turns off storage capabilities, QuotaExceededError exception is thrown. Below code is to be used to prevent an exception to the user.

try {
localStorage.setItem('firstName', $('#firstName').val());
} catch(e) {
// degrade gracefully
}

Currently, only string values can be stored in web storage, but sometimes we might need to store arrays or JavaScript objects. To accomplish this,  we need to use JavaScript Object Notation (JSON) utility methods.

The following example creates a JSON object and uses the stringify() method to convert the value to a string that can then be placed in web storage and use the parse() method to deserialize a new instance of the object from the string representation of the object that was stored

var person = { firstName: sreekanth', lastName: boya' };
localStorage.setItem(‘person', JSON.stringify(person));  
var person = JSON.parse(localStorage.getItem(‘person '));

localStorage is designed to retain data across multiple sessions.

sessionStorage is a Web Storage to store the data. It retains data for a single session only. If the user closes the browser window, records stored are automatically cleared. This is an important advantage because only a limited amount of space is available.

SessionStorage is firmly dedicated to their respective browsing contexts. sessionStorage has a context that, by design, is extremely confined. It’s limited to a single browser tab or window. Its data cannot be passed from one tab to the next. However, the data can be shared among any <iframe> elements that exist on the page.

Code to show the usage of sessionStorage

window.onload = function() {
     var currDate = new Date();
     sessionStorage.setItem("currenttime", currDate.toLocaleString());
}
function updateHTML() {
document.getElementById("currenttime").innerHTML= sessionStorage.getItem("currenttime");
}

Expect to come across this popular question in HTML technical interview questions.  

XSS Attack: XSS refers to client-side code injection attack where an attacker can execute malicious scripts by making use of unvalidated or unencoded user inputs in web applications. This malicious scripts may attempt to steal sensitive information from the user visiting the website. We need to prevent attack by filtering user inputs using blacklisting(not allowing users to input character sequences such as <, >, <script> etc.).

Different type of XSS attacks :

Stored or Type 1 XSS attacks: Stored XSS attacks in which the supplied malicious input from the attacker is persisted and stored in the back-end database or repository. Whenever that content is retrieved and rendered to be displayed on the web page, the browser is completely unaware of it and it either executes the malicious JavaScript that comes from the database or renders the malicious HTML markup, instead of displaying it as text. The stored XSS will remain permanently in the database and will impact all users visiting the affected web page.

Reflected or Type 2 XSS attacks: Reflected XSS attacks are the second type of XSS attack vector, in which the malicious XSS payload is not stored in the database table for persistence, but is still injected in some parameter of the web page that gets rendered back to the user. The browser, unaware of this change, simply either renders the injected malicious HTML or executes the injected malicious Javascript code, again resulting in the user's data being compromised.

DOM-based or Type 0 XSS attacks: A document object model-based XSS is the third category of XSS attacks. Here, the XSS payload is not sent to the server, but due to implementation flaws and changing the state/DOM of the web page with the help of client-side JavaScript, an attacker paces the payload that gets picked up with the JavaScript responsible for manipulating the state of the web page.

Prevention Methods: 

✓ Output encoding: Escaping any character a user enters before displaying it.

✓ Filtering inputs using whitelisting: Only allow characters (e.g, A–Z and 0–9) to be entered.

✓ Filtering inputs using blacklisting: Not allowing a user to enter character sequences such as <script> or even < and > characters.

Placeholder: The placeholder attribute can only contain text, not HTML markup.   However, there are some vendor-specific CSS extensions that allow you to style the placeholder text in some browsers.  Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

Here’s how you can include placeholder text in your own web forms:

<form>
 <input name="q" placeholder="Go to a Website">
 <input type="submit" value="Search">
</form>

You can use Microsoft Internet Explorer conditional comments to load a style sheet created exclusively for Internet Explorer. You can place a conditional comment in <head> after all links to other style sheets. Inside the conditional comment, you can place a link to a style sheet. I call this the conditional style sheet. Since the conditional stylesheet comes last, it overrides previously loaded styles. You can create a separate conditional stylesheet for Internet Explorer 6, and if necessary you can create one for Internet Explorer 7. You can include styles in this stylesheet to compensate for different behaviors and bugs.

The following pattern loads two conditional style sheets. The first is for Internet Explorer versions 6 and earlier. The second is for Internet Explorer 7 and higher. Internet Explorer 7 fixes most of the bugs in Internet Explorer 6, but there are still a number of CSS features that it does not implement, such as the content property.

HTML

<!--[if lte IE 6]>
<link rel="stylesheet" href="ie6.css" media="all"
type="text/css" />
<![endif]-->
<!--[if gt IE 6]>
<link rel="stylesheet" href="ie.css" media="all"
type="text/css" />
<![endif]-->

Markup a document with block elements to identify its structure. There is meaning in structure, and HTML markup is most meaningful when its structure reflects the hierarchy and relationships of a document’s topics.

Because a parent element contains child elements, they are related structurally. This implies their content is related. For example, a child’s content is typically a subtopic of its parent’s topic, and siblings typically have related subtopics. Implicit in the hierarchical nature of HTML is the assumption that document organization is hierarchical.

Structural blocks may contain block elements only. They have structural meaning, but they have little semantic meaning. In other words, they do not tell you what something is; they tell you how it is organized.

There are four major structural block elements (<ol>, <ul>, <dl>, and <table>) with nine supporting structural elements (<li>, <dt>, <dd>, <caption>, <thead>, <tfoot>, <tbody>, <colgroup>, and <col>)

HTML supplies the class and id attributes for these purposes. We can assign a class and an id to any element. An ID and class name cannot include a space. It must start with a letter and may contain letters, numbers, the underscore (_), and the dash (-). Since CSS selectors are case-sensitive when using XHTML, it is a common practice to use lowercase class and ID names.

#id { STYLES }
*.class { STYLES }

It's no surprise that this one pops up often in HTML basic interview questions.

Apply styles to chosen class or ID as follows:

  • Use the type selector to select all elements of a particular type. The type selector is the element’s name without the less-than and greater-than signs.
  • Use the class selector to select all elements that you have assigned to a class. The class selector is the period followed by the name of a class. The class selector is added to the end of a type selector. You can add it onto the end of the universal selector, *, to select all elements in the document that have a matching class, such as *.my-class1. You can also use the class selector all by itself, such as .my-class1, which is a shortcut for *.my-class1.
  • Use the ID selector to select all elements in the document assigned to that ID. Each element has one ID, which should be unique in a document.

HTML

  • type { STYLES }
  • *.class { STYLES }
  • #id { STYLES }

Below are the few best practices to improve the performance of the page load time.

  • Make Fewer HTTP Requests
    • Implementing parallel HTTP requests will improve performance.
    • Combining smaller resource files and creating a single file will reduce the number of HTTP requests.
    • Use Image sprites to combined image files and delivering content more quickly over the browser’s relatively low number of parallel connections.
  • Use a Content Delivery Network (CDN)
    • Putting all that static content close to the user can really speed up performance.
  • Avoid Empty src or href Attributes
    • Avoid creating an img element with an empty src attribute and then dynamically assign the value of the src attribute during page load with JavaScript. With this approach, the elements always get evaluated before scripts get run. The browser tries to evaluate that empty attribute and creates an HTTP request to do so.
    • A similar pattern and problem appear for href attributes, usually in anchor elements. If the href attribute is blank, the browser sends an HTTP request to the server when the user triggers the interaction. That doesn’t affect page load time, but it does create needless traffic on the servers,
    • wasting bandwidth and potentially slowing delivery for all visitors. The simple fix for this problem is to set the value of the href attribute to a JavaScript command like <a href="javascript:;" class="triggerName">Trigger</a>
  • Add Expires Headers
    • Adding an Expires header with a date far in future to all your static components (images, stylesheets, scripts, flash, PDF, and so on) lets the static content be cached by browsers. The browsers won’t have to fetch the static content for subsequent visits and they’ll have a much faster loading time.

E.g: Expires: Wed, 1 Jan 2020 00:00:00 GMT

  • Compress Components with GZIP
    • Using the “Accept-Encoding” header, the content in the HTTP request can be compressed. Such a header appears as below
    • Accept-Encoding: gzip, deflate.

The header specifies two kinds of compression. GZIP is more common because it is the most effective compression scheme available. GZIP reduces the size of a response by about 70%.

  • Put CSS at the Top

If the page contains style information, put that information at the top (in the head element). To avoid redrawing many web browsers won’t start rendering a page until the browser has all the style information.

  • Put JavaScript at the Bottom
  • Avoid CSS Expressions
  • Remove Unused CSS
  • Minify JavaScript and CSS
  • Minimize Redrawing

There are various elements used in HTML to build a web page. All the elements fall in two categories i.e either they are block level elements or inline elements.

  • Block Level Elements:

Block level elements are elements which start in a new line and occupy the whole available horizontal space of the parent element, it stretches both on the left and right as far as it can.

Examples of block level elements are:

<div> is used as a block level element.It always starts in a new line.

<p> p element or the paragraph element is also used as a block level element as it takes the whole available space.

In the same way header, footer, aside, address, section all these are block level elements that takes whole available space both in the right as well as in the left.

  • Inline Elements:

Inline elements are elements which only take the width required to fit into the line. If we have two inline elements, then each will take the width required by it to fit in the line. When they cannot fit in the line, they generally wraps to the next line.

Some, inline elements are <span>, <a>, <b>, <label>

In the below code, we have two <div> and 7 <span> elements.

<!DOCTYPE html>
<html>
<head>
   <title>Block Inline Demo</title>
</head>
<style>
div, span{
   font-size:1.5rem;
}
</style>
<body>
    <div>Lorem?</div>
    <div>ipsum?</div>
    <span>dolor</span>
    <span>amet</span>
    <span>consectetur</span>
    <span>adipisicing</span>
    <span>Quidem</span>
    <span>quibusdam</span>
</body>
</html>

Save the above code as demo.html and open in any browser. You can see that the <div> elements takes their one line, whereas the <span> elements are all in one line.

demo.html

Semantic elements are the tags which have both meaning to the browser and developer. In other words, semantic elements are the tags in plain English which says what it does.

Example consider <div> and <span> which says nothing about what they do or what they are to a normal person. They are non-semantic elements.

On the other hand, elements like <form> and <table> tells what they are and do exactly the same thing. They are semantic elements.

Some of the Semantic elements with their brief descriptions are -

  • <article>- It specifies some content on the website. Used to wrap an article like a blog post on the site.
  • <section>- It specifies some section in article. An article can have many paragraphs and they should be wrapped in section tag.
  • <header>- It specifies the header section in the website. It is use to wrap the content, which will form the header for the site.
  • <footer>- It specifies the footer section of the website. Generally contains the contact us, copyright information.
  • <nav>- It is used to wrap all Navigation part of your website. All the navigation links should be put here.
  • <aside>- It is used to wrap all the content of the website, which will be in the sidebar. In most websites sidebar contains advertisements and aside can be used to wrap them.
  • <main>- It specifies the main content of the website. It will wrap all your articles and other section.
  • <figure>- It is used to wrap an image tag and convey the message that the following contains images. It is generally used with fig caption tag.
  • <figcaption>- It is used inside a figure tag along with image tag and is used to specify the caption.

Below is an example of a website created using semantic elements.

<!DOCTYPE html>
<html>
<style>
nav{
   background: yellow;
   padding: 2%;
   font-size:1.2rem;
}
footer{
   background: yellow;
   padding: 1%;
   font-size:1rem;
}
main, header{
text-align: center;
}
</style>
<body>
   <nav>
       <a href="https://en.wikipedia.org/wiki/Google_Chrome">Chrome</a> |
       <a href="https://en.wikipedia.org/wiki/Firefox">Firefox</a> |
       <a href="https://en.wikipedia.org/wiki/Safari_(web_browser)">Safari</a> |
       <a href="https://en.wikipedia.org/wiki/Internet_Explorer">Internet Explorer</a>
   </nav>
   <header>
       <h1>Web Browsers</h1>
       <p>Google Chrome and Firefox are the most used browsers today.</p>
       <hr>
   </header>
   <main>
       <article>
           <section>
               <h1>Google Chrome</h1>
               <p>Google Chrome is a free, open-source web browser developed by Google, released in 2008.</p>
               <figure>
                   <img src="https://source.unsplash.com/900x600/?nature" width="100%" alt="Nature">
                   <figcaption>Random Nature image</figcaption>
               </figure>
           </section>
           <section>
               <h2>More Information</h2>
               <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                   Unde consequatur doloremque reiciendis saepe! Iure dicta
                   harum molestias laborum accusantium reprehenderit
                   sunt, repudiandae eos aut itaque dolores et repellendus.
                   Dignissimos, voluptate.
               </p>
               <hr>
           </section>
       </article>
       <article>
           <section>
               <h1>Mozilla Firefox</h1>
               <p>Firefox is a free, open-source web browser from Mozilla, released in 2004.</p>
               <figure>
                   <img src="https://source.unsplash.com/900x600/?water" width="100%" alt="Water">
                   <figcaption>Random Water image.</figcaption>
               </figure>
           </section>
           <section>
               <h2>More Information</h2>
               <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                   Unde consequatur doloremque reiciendis saepe! Iure dicta
                   harum molestias laborum accusantium reprehenderit
                   sunt, repudiandae eos aut itaque dolores et repellendus.
                   Dignissimos, voluptate.
               </p>
           </section>
       </article>
   </main>
   <footer>
       <p>Posted by: Sam Paul</p>
       <p>Contact information: <a href="mailto:someone@example.com">
               someone@example.com</a>.</p>
   </footer>
</body>
</html>

Web Browsers

Save the above code as demo.html and open in any browser.

There are no rules for HTML structure and web-page will not throw an error if we don’t follow structure. But then also there are a set of rules which are the de-facto standard to create a webpage.

  • <DOCTYPE>

The first tag to be used in a web-page is the doctype tag. It is used for historical reasons and its purpose is to prevent the browser to switch to quirks mode. In the old days of the web pages were written for two browsers of the time - Netscape Navigator and Internet Explorer. When web-standards were made by W3C, the <doctype> tag was used to tell the browser to run the following web-page in full mode, instead of quirks mode for Netscape Navigator and Internet Explorer. The latest way described in HTML5 is to use <!DOCTYPE html> at the top of your web-page.

  • <html>

After the <!DOCTYPE html>  we wrap our entire code inside a pair of <html>…</html> tags.

  • <head>

The head tag is mainly meant for the browser and not directly rendered. It contains <title> tag, which is the title of the web-page. It also contains <meta> tags, which contains various information for the web-page. Also contains <script> tag to link external javascript files and can also contain <link> tag to link external stylesheets.

  • <body>

It contains the main body for our page. The code inside it is what we see in our web-page. In the body tag, we can contain all our elements normally or can organize it in a better way using semantic tags.

And below is an example for-

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Our Title</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
   <script src="main.js"></script>
</head>
<body>
   <h1>Our header</h1>
   <p>Lorem ipsum dolor sit.</p>
   <h2>First Section</h2>
   <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt, culpa?</p>
   <h2>Second Section</h2>
   <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aut, ratione?</p>
</body>
</html>

Header file

Save the above code as demo.html and open in any browser.

A staple in React Interview Questions, be prepared to answer this one.

Meta tag is used to describe the data in the webpage. Metadata literally means data about data. One of the most popular uses of the meta tag is to increase the SEO(Search Engine Optimisation) so that your website comes on the top of google search. the clever use of meta tag can do that but it is more than that.

<meta> tags are included in the webpage by placing it inside <head>..</head> in your webpage. They contain various attributes which define them.

Keywords

This attribute is used to specify the keywords used in your web-page. It is used by crawlers from search engines like google to find sites. So, giving the right keyword is very necessary for good SEO.

<meta name=“keywords” content=“HTML, Meta, Metadata, Meta tutorial” />

Description

This attribute is used to describe the content of your web-page. It is again used by search engines like google to index your site. So, giving the right description of your website is also very important for SEO.

<meta name=“description” content=“Learn Meta in one hour” />

Revision Date

This attribute is used to give the last revision date of your website. It is used by browsers to refresh your page. Browsers generally keep the cached version of the website for displaying, so if the revision date is updated it will refresh its version in your computer.

<meta name=“revised” content=“MetaTutorials, 5/9/2019” />

Refreshing

This attribute is used to notify the browser to refresh your website after the mentioned duration. It is used by browsers to refresh your page. Browsers generally keep the cached version of the website for displaying, so this attribute will force the browser to refresh our site after the mentioned time in seconds.

<meta http-equiv=“refresh” content=“300” />

Redirection

You can use the refresh attribute to redirect your website to some other webpage, after the mentioned duration in seconds. It is done by adding an additional URL to the content. The below example will redirect your website to sometutorial.com after 5 seconds.

<meta http-equiv=“refresh” content=“5, url=“sometutorial.com” />

Cookies

Cookies are data stored in your computer web-browser and are exchanged with the web-server which hosts the site. One of the most common use is to store your authentication details on the web-browser and use it to communicate with the server so that you don’t have to enter credentials every time. In the cookie attribute for meta, we mention the time till the cookies will be stored in your system.

<meta http-equiv=“cookie” content=“userid = nabs;  expires = Wednesday, 08-Aug-22 23:59:59 GMT;” />

Author

This attribute is used to set the author name of your web-page. It is again used by search engines like google.

<meta name=“author” content=“Hiren Pandey” />

Character Set

This attribute is used to specify the character set of your web-page. By default, web-servers uses ISO-8859-1 (Latin1) encoding to process your web-page. This is an old encoding with very limited 256 characters. You can use the more modern UTF-8 encoding by this attribute or if your website is in Chinese you can use Big5 encoding.

<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
<meta http-equiv = "Content-Type" content = "text/html; charset = Big5" />

Viewport

A very important attribute which sets the viewing area, as per the device you are rendering your web-page. So by using this website, it becomes a bit responsive by itself and adjusts it according to devices.

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

Now, we will make a complete web-page with these meta tags including the amazing viewport also.

<!DOCTYPE html>
<html>
<head>
   <title>Meta tutorials</title>
   <meta name="keywords" content="HTML, Meta, Metadata, Meta tutorial" />
   <meta name="description" content="Learn Meta in one hour" />
   <meta name="revised" content="MetaTutorials, 5/9/2019" />
   <meta http-equiv="refresh" content="300" />
   <meta http-equiv="cookie" content="userid = nabs;  expires = Wednesday, 08-Aug-22 23:59:59 GMT;" />
   <meta http-equiv="Content-Type" content="text/html; charset = UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
   <h1>Meta tutorials</h1>
   <p>Meta tag is used to describe the data in the webpage. Metadata literally means data about data.
       One of the most popular uses of the meta tag is to increase the SEO(Search Engine Optimisation)
        so that your website comes on the top of google search. A clever use of meta tag can do that but it is more than that.
    </p>
    <figure>
           <img src="https://source.unsplash.com/900x600/?water" width="100%" alt="Water">
           <figcaption>Random Water image.</figcaption>
   </figure>
   <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Delectus sunt voluptatem
       placeat doloribus aperiam ipsum incidunt, a in aliquam ab.</p>
</body>
</html>

Save the above code as demo.html and open in any browser.

Now, resize the browser to check the mobile view. You can see the viewport meta tag in play and will add responsiveness to the web-page.

While surfing net, we come across many websites to get the information which we want to get, along with this we also come across some websites which have formed in the bottom or they pop up a form for the user to enter his/her information.

To create a form in our website we use the <form> tag. Inside the form tag, we create text area, checkbox,  radio buttons, Drop down buttons, etc to gather the information of the site visitor. Generally, once the user fills the form and clicks the Submit button, all the data is taken and send to some backend server. On the backend server, it is stored in some database.

The <form> tag have two important attributes - action and method. The action attribute specifies the backend script to process your data like a PHP script. The method specifies the method for API calls - mostly GET or POST.

The form example is below.

<!DOCTYPE html>
<html>
<head>
   <title>Form tutorials</title>
   <style>
       form{
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
   <form action="/action_page.php" method="get">
       <h1>Complete Form</h1>
       <div class="form-example">
           <label for="name">Enter your name: </label>
           <input type="text" name="name" id="name" required>
       </div>
       <div class="form-example">
           <label for="email">Enter your email: </label>
           <input type="email" name="email" id="email" required>
       </div>
       <div class="form-example"></div>
           <label for="desc">Enter your description: </label>
           <br>
           <textarea id="desc" rows="5" cols="35" name="description">
                       Enter description here...
                    </textarea>
       </div>
       <div class="form-example">
           <input type="submit" value="Subscribe!">
       </div>
   </form>
</body>
</html>

<iframe> tag is also called HTML inline frame element. It is generally used to display the content of another website inside our web-page. One of the most common uses is to display maps, inside our webpage. We are doing the same in our example.

The <iframe> tag have many attributes like - src, width, height.

  • The src attribute is the address of the website you want to display.
  • The width and height specify the dimensions of the iframe.
<!DOCTYPE html>
<html>
<head>
   <title>iframe tutorials</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
<div class="grid__iframe">
       <h1>Bangalore Map</h1>
       <iframe width="980" height="600"
       src="https://www.openstreetmap.org/export/embed.html?bbox=77.24761962890626%2C12.746176829427839%2C77.82440185546876%2C13.231924637991806&amp;layer=mapnik"
       style="border: 1px solid black">
   </iframe>
</div>
</body>
</html>

Bangalore map

HTML5 introduced the feature to store data in the browser. This is a very useful feature, which can be used by developers to store user data when they visit the site.

There are two types of Web Storage in HTML5 -

  • Session Storage - As the name suggests, it stores data only for the current session. In other words, the data stored will be cleared once we close the browser.
  • Local Storage - It is another type of Web Storage and the data stored in local storage, doesn’t gets cleared even when the browser is closed.

The local storage can be accessed using localStorage and session storage can be accessed using sessionStorage. In the below example, we are storing the number of hits in both localStorage and sessionStorage. But if we close the browser, the Session Storage count again starts from 1 but in Local storage, it persists.

<!DOCTYPE html>
<html>
<head>
   <title>Web storage</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
       <script type="text/javascript">
       window.onload = function(){
           if (sessionStorage.hits) {
               sessionStorage.hits = Number(sessionStorage.hits) + 1;
           } else {
               sessionStorage.hits = 1;
           }
           if( localStorage.hits ) {
               localStorage.hits = Number(localStorage.hits) +1;
            } else {
               localStorage.hits = 1;
            }
           document.getElementById("local").innerHTML = `Total Hits Local Storage: ${localStorage.hits}`;
           document.getElementById("session").innerHTML = `Total Hits Session Storage: ${sessionStorage.hits}`;
       };
       </script>
</head>
<body>
   <div class="grid__iframe">
       <h1>Refresh the page to increase number of hits.</h1>
       <h2>Close the window and open it again</h2>
       <h4>The Local Storage Count will remain, but Session storage will start from 1</h4>
       <div id="session"></div>
       <div id="local"></div>
   </div>
</body>
</html>

<canvas> tag helps the user to draw anything in the canvas area. It is generally used in creating graphics or animation in the page.

Game graphics and other visual images can be created using the tag canvas>. Inside the <canvas> tag we can also specify the height and width attributes.

Below is an example for creating two simple overlapping squares of different colors. We create a <canvas> tag in our HTML, then the rest of coding is in the JavaScript. Here, first, we take the id then we tell the browser it's a 2d canvas by canvas.getContext('2d').

Then we convey the colour by fillStyle and the dimensions of the rectangle by fillRect(10, 10, 100, 100), which means it will start at position 10,10 and width and height of 100.

<!DOCTYPE html>
<html>
<head>
   <title>Canvas Demo</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
   <script type="text/javascript">
       window.onload = function () {
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
           //square 1
            ctx.fillStyle = 'green';
            ctx.fillRect(10, 10, 100, 100);
           //square 2
            ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
            ctx.fillRect(50, 50, 100, 100);
       }
   </script>
</head>
<body>
   <div class="grid__iframe">
        <canvas id="canvas" width="300" height="300">
            This canvas shows two overlapping squares.
        </canvas>
   </div>
</body>
</html>

canvas tag

The topic of the canvas is very large and we can create some complex shapes and also render animation on the web-page.

We can display a code block in our HTML using the combination of <pre> and <code> tag. The <code> tag only represents a single line and if we wrap our complete code in the <code> tag, it will be displayed in a line.

So, we use it in combination with <pre> tag. We basically wrap everything inside a <pre> tag. The <pre> tag stand for reformatted test. So, anything we give inside it including line breaks will be shown.

We will add some code to display in our canvas example in Question 18.

<!DOCTYPE html>
<html>
<head>
   <title>Code Demo</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
       h1,h4{
           text-align: center;
       }
   </style>
   <script type="text/javascript">
       window.onload = function () {
           var canvas = document.getElementById('canvas');
           var ctx = canvas.getContext('2d');
           //square 1
           ctx.fillStyle = 'green';
           ctx.fillRect(100, 10, 100, 100);
           //square 2
           ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
           ctx.fillRect(150, 50, 100, 100);
       }
   </script>
</head>
<body>
   <div class="grid__iframe">
       <h1>HTML Canvas</h1>
       <canvas id="canvas" width="300" height="300">
           This canvas shows two operlapping squares.
       </canvas>
       <h4>Code for the canvas</h4>
        <pre>
            <code>
                window.onload = function () {
                    var canvas = document.getElementById('canvas');
                    var ctx = canvas.getContext('2d');
                    //square 1
                    ctx.fillStyle = 'green';
                    ctx.fillRect(100, 10, 100, 100);
                    //square 2
                    ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
                    ctx.fillRect(150, 50, 100, 100);
                }
            </code>
        </pre>
   </div>
</body>
</html>

HTML Canvas

A common feature of any website, even the most basic static site is a Contact Us form. Here, the user will enter his/her basic information and when clicked on Submit, it will send an email to us.

This feature can be implemented very easily using mailto in attribute action of a form. Below is a simple Contact Us form containing this mailto.

<!DOCTYPE html>
<html>
<head>
   <title>Code Demo</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
   <div class="grid__iframe">
       <h1>Contact Us</h1>
       <form enctype="text/plain" method="post" action="mailto:someone@someone.com">
           Your First Name: <input type="text" name="first_name"><br>
           Your Last Name: <input type="text" name="last_name"><br>
           Comments: <br>
           <textarea rows="5" cols="35" name="comments"></textarea>
           <br>
           <input type="submit" value="Send">
       </form>
   </div>
</body>
</html>

It uses your local email client of the computer to send an email, once we click on submit. On a Mac, it will open the default “Mail” client as shown in the screenshot.

 mailto in HTML format

Intermediate

The various tags provided for better structuring in HTML5 are:

  • <header> - This tag is used to define a header for a document or section
  • <footer> - This tag defines a footer for a document or section
  • <section> - It defines a section in a document
  • <summary> - It provides a visible heading for a <details> element.
  • <details> - It defines additional details that can be viewed or hidden by the user
  • <command> - It defines a command button to be invoked by the user
  • <hgroup> - When there are multiple levels in a heading, it groups a set of <h1> to <h6> elements.
  • <dialog> - It defines a dialog box.
  • <figure> - This tag specifies content like illustrations, diagrams, photos, code listings, etc.
  • <figcaption> - It is used to provide a caption for a <figure> element
  • <article> - This tag defines an article.
  • <aside> - It defines content other than the page content.
  • <bdi> - This tag isolates a part of text for formatting in a different direction from other text.
  • <mark> - It defines highlighted text.
  • <meter> - It defines a scalar measurement within a known range.
  • <nav> - It defines links for navigation.
  • <progress> - This tag exhibits the progress of a task.
  • <ruby> - It defines a ruby annotation for East Asian typography.
  • <rt> - It defines an explanation/pronunciation of characters for East Asian typography.
  • <rp> - This tag tells the system what to display in browsers that do not support ruby annotations.
  • <time> - This tag defines a date/time.
  • <wbr> - This tag defines a line-break.

List of new Media Elements that have been added in HTML5 are :

  • <audio> - It defines sound content
  • <video> - It defines a video or a movie
  • <source> - This tag defines the multiple media resources for <video> and <audio>
  • <embed> - It provides a container for an external application or interactive content
  • <track> - It defines text tracks for <video> and <audio>.

No character encoding declared at the document level for below document can be as below.

  • Original Code
<!DOCTYPE html>
<html>
     <head>
<title>HTML5 Programming</title>
     </head>
     <body>
     <body>
</html>
  • Corrected Code

This can be fixed by declaring the Character Set. Use UTF-8 Character encoding and add this markup to head section.

<!DOCTYPE html>
<html>
     <head >
           <meta charset ="UTF-8">
<title>HTML5 Programming</title>
     </head>
     <body>
     <body>
</html>

Example

<!DOCTYPE html>
<html>
     <head>
           <meta charset ="UTF-8">
           <title>Block Level Elements</title>
     </head>
     <body>
           <p>I am a paragraph</p>I am directly after the paragraph
     <body>
</html>

OutputExample to display the text in two paragraphs

Example

<!DOCTYPE html>
<html>
     <head>
           <meta charset ="UTF-8">
           <title>Block Level Elements</title>
     </head>
     <body>
           <h1>Level 1 Heading</h1>
           <h2>Level 2 Heading</h2>
           <div>This is a logical divison<div>
           <hr>
           I will have a horizantal rule above me
           <ol>
<li>I am part of an ordered list</li>
<li>li stands for list item</li>
<li>You can add as many as you want</li>
           </ol>
           <ul>
<li>I am still a list item</li>
<li>This time I am inside an un-ordered list</li>
<li>Notice how I'm rendered in the browser</li>
           </ul>
     <body>
</html>

OutputBlock-level Elements output

The Strong and em tags are new semantic inline elements  to specify the relative importance of their content. Search engines use <em> and <strong> to rank content.

<em> was emphasis and is now for stress emphasis, such as something pronounce differently.  The “stress” being referred to is linguistic; if spoken it would be emphasized pronunciation on a word that can change the nuance of a sentence.

For example "Call a doctor now!" stresses doctor, perhaps in reply to someone asking "She looks thirsty, should I call a homoeopath?" In comparison, "Call a doctor now!"  changes the emphasis on doing so quickly.

<strong> was for stronger emphasis and is now for strong importance for its content. Strong indicate relative importance by  nesting <strong> elements

Example 

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Text Modifiers</title>
    </head>
    <body>
          The <strong>strong tag</strong> will render bold text.
          <br>
          The <em>em tag</em> will render italic text.
    <body>
</html>

OutputText Modifiers – strong and em Tags output

An image can be inserted into the document using <img>. Use the src attribute to specify the URL containing the image. alt attribute (alternative attribute) is used to provide a brief description of the image. This alternative description should be written specifically for screen readers to read and for displaying when the image fails to download. Decorative images are best displayed as background images, but if we need to use a decorative <img> element, include the alt attribute, but leave it empty.

Because a browser downloads each image separately, it needs to know the image’s height and width so it can create a placeholder for the image while the image downloads. Otherwise, after each image is downloaded and its real size becomes known, a browser has to reflow the page. This slows the rendering and annoys the user. To set an image’s size, we can use the width and height attributes of <img> or the width and height CSS properties.

Example:

<img src="FILE.EXT" width="IMAGE_WIDTH" height="IMAGE_HEIGHT" alt="BRIEF_IMAGE_DESCRIPTION" />

<aside>:  Piece of content that is tangentially related to the content that surrounds it but isn’t essential for understanding that content. <aside> content should be added to the main content; that is, any related content. While print design can provide inspiration, don’t stop at pull quotes.

For example, a footnote provides extra but unessential information, and a pull quote (while essential content) is a quoted copy of the text from the main content. However, keep in mind the <aside> must be related. Having your site’s sidebar in an <aside> as a child of <body> is fine, but site-wide information shouldn’t appear in an <aside> that is the child of an <article>, for example. Also, <aside> would be appropriate for advertising, as long as it was related to the parent sectioning element. Here is an example <aside> providing extra information in the margin of an article.  

Example

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Images</title>
      <style type="text/css">
       h1 { font-size:160%; font-weight:bold; }
       aside, section, article { display:block;  }
       section { width:400px; margin:auto; }
       article { width:405px; text-align:left;  }
       aside { width:200px; padding:5px; margin:5px 5px 5px 5px; float: right; border:1px black solid; }
    </style>
    </head>
    <body>
          <article>
         <h1>Which OS are you using?</h1>
         <section>
             <b>The answer is all of them.</b> If you survey a group of people you will
                     get very different answers…IWindows 10.
                  <aside>Majority of the people use Windows 10. </aside> macOS, Linux and mobile operating systems are available
         </section>
          </article>
    <body>
</html>

Output

This <mark> element is fused to highlight or draw attention without changing its importance or emphasis. The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. Below are the different use cases.

  • Indicating a searched-for word or phrase in a search results page.
  • Indicating a specific code of interest in a code sample such as a change that’s discussed in the surrounding text.
  • Highlighting part of a quotation that wasn’t emphasized in the original.

Example 

<p>While Remy and Bruce did a masterful job on <mark>&lt;cite&gt;</mark>Introducing
HTML5<mark>&lt;/cite&gt;</mark>, I’m not sure about that shade of brown.</p>

While Remy and Bruce did a masterful job on <cite>Introducing HTML5</cite>, I’m not sure about that shade of brown.

Cookies will continue to be an effective tool for the foreseeable future, but they have some drawbacks.

  • Capacity limitations: Cookies are limited to about 4 KB of data, which is not large, although we can create more than 30 cookies per site. (The actual maximum limit depends on which browsers you are targeting; the average is between 30 and 50.)
  • Overhead: Every cookie is sent with each HTTP request/response made, regardless of whether the values are needed. This is often true even for requests for static content (such images, css files, and js files), which can create heavier-than-necessary HTTP messages.

Contenteditable attribute allows the user to edit any of the text contained within the element, including its children. User can edit a simple to-do list and store them using local storage.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>untitled</title>
</head>
<body>
   <h2> To-Do List </h2>
    <ul contenteditable="true">
       <li> Break mechanical cab driver. </li>
       <li> Drive to abandoned factory
       <li> Watch video of self </li>
    </ul>
</body>
</html>

Below are the best practices to be followed to create a practical and maintainable CSS.

  • Think in terms of components, not pages.
  • Think about types of things, not individual things.
  • Prefer classes to IDs.
  • Create composable classes.
  • Use descendent selectors to avoid redundant classes.
  • Keep the selectors as short as possible.
  • Order the CSS rules loosely by specificity.
  • Prefer percentages for internal layout dimensions.

HTML stands for Hyper Text Markup language. It along with CSS and JavaScript forms the founding stone of the Internet. All web-pages are written in HTML, as this is the language understood by most web-browsers. It is the most essential part, as for a web-page CSS and JS are not essential.

An HTML document consists of HTML tags and saved with .html. These tags are created and new tags are added to HTML by standard committee World Wide Web Consortium (W3C).

An example of a simple HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Example</title>
</head>
<body>
   <h1>Header</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur odit quaerat,sapiente consectetur temporibus dolores placeat facere ipsa, illum deleniti minima,quas exercitationem tenetur quibusdam ducimus veniam! Explicabo modi iusto minus,    tenetur facere consequatur quasi id ea, debitis eum quae, odit saepe corporis repellat ad provident! Ex hic sed alias!
   </p>
</body>
</html>

On opening it in a browser.

Header

Several new elements and attributes were introduced in HTML5 which helps us in building

attractive websites.

Following new features are supported by HTML5:

  • New Semantic Elements: Elements like header, footer article, section, aside, main, etc. are offered in HTML5. These all together convey the purpose of elements and the type of content inside both to the developer and the browser.

New Semantic Elements

  • New Form Types – Other than standard form input types few more new form input types are supported by HTML5 such as date, time, week, month, number, range, email, URL, etc.
  • Video and Audio – Through these new tags, you can embed a video in your website. It also supports audio tags through which you can embed sound in your website.
  • Local Storage – Web applications can store data locally within user's browsers with the help of Local Storage. It is more secure and locally large amount of data  can be stored without hampering the performance of the website.
  • Drag and Drop Features – This is a new feature introduced in HTML5 you can drag an object to new location with the help of this feature.
  • Elements:

A web page has many segments, such as paragraph, image, link or anything through which you can interact is known as elements. Each element has its own purpose -  for example you can click on a link or write on a text box.

  • Tags:

The HTML document is a text document which can be opened  with any text editor in a computer. When we open the document we see that there are many tags used to build the document. These Tags are actually keywords surrounded  by angled brackets and each one of them describes an element.

Most of the tags have opening and closing tags

  • Tags:

Keywords used to format a web-browser are known as tags.

Example: (Start Tag) <p>...</p> (End Tag).

  • Elements:

When content is inserted between the Start Tag and End Tag this is known as Element.

Example: (Start Tag) <p>This is element of HTML</p> (End Tag).

Attributes are special words generally used inside the opening tag to control the behaviour of the elements. It provides additional information about an element. These are used as modifiers of a anTML element type.

Attributes comes in name/value pairs in the format name=“value”. Both attributes name and values are case insensitive, but W3C recommends lower case for both.

There are some pre-defined attributes which are associated with specific tags only like src, alt, and href. We will look into them first.

HTML links are created using <a> tag. It have a special href attribute, which specifies the address to open when the link is clicked.

<a href=“http://www.google.com”>Search</a>

HTML images are created using <img> tag. The file to be open is specified using src attribute.

<img src=“../images/sunset.jpg”>

HTML images can have 3 other attributes also. They are width, height and alt. The attribute width and height specifies the width and height of the image, and is generally used to make a larger image small. The alt attribute mainly does two things. One, if for some reason the web-page is not able to open the image it will show the test inside alt attribute. Secondly, it is read by screen-reader used by vision imparted person.

<img src=“../images/sunset.jpg” width=“300” height=“300” alt=“A beautiful sunset”>

The next three attributes - class, id and style are used extensively in html tags and are generally used with any tag.

The class attribute is generally used when we need to apply the same style to more than one html tags. We use the same class name in them and then style it in css.

The id attribute is used when we need to identify an element/tag as unique. We can have only one id name attribute used through our HTML, but can have one class name used at many places.

The style attribute is used to inline CSS styles within the element/tag. Example of all three attributes are in below code.

<!DOCTYPE html>
<html>
<head>
   <title>The Attribute Demo</title>
</head>
<style>
.page__heading{
   font-size: 1.5rem;
   color:blueviolet;
}
.alt__para{
   font-size: 1.2rem;
   color:chocolate;
}
</style>
<body>
   <h1 id="page__heading">Heading</h1>
   <p class="alt__para">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Doloribus, quis?</p>
   <p style="font-family:arial; color:#FF0000;">Lorem ipsum dolor sit amet.</p>
   <p class="alt__para">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem, quibusdam!</p>
</body>
</html>

Save the above code as demo.html and open in any browser.

demo.html

Comments in any programming language is used by developers to keep track of what the next block of code will do or means. It is very useful when the project grows big and many developers work on it. A well commented code can be easily understood by all other developers working on the project, then the one who wrote it.

Comments are ignored by the compiler which runs the code, and in case of HTML it’s the browser. HTML comments are a bit different than other languages. In JavaScript we can comment a line by using //.

Whereas in HTML to comment a line(s) we place it between <!— and —>. We will add comments to our demo.html file from Question 4.

<!DOCTYPE html>
<html>
<head>
   <title>The Attribute Demo</title>
</head>
<style>
.page__heading{
   font-size: 1.5rem;
   color:blueviolet;
}
.alt__para{
   font-size: 1.2rem;
   color:chocolate;
}
</style>
<!--Body starts here-->
<body>
   <h1 id="page__heading">Heading</h1>
   <p class="alt__para">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Doloribus, quis?</p>
   <!--Below is an example of inline styling,
    which can be used directly in HTML tags-->
   <p style="font-family:arial; color:#FF0000;">Lorem ipsum dolor sit amet.</p>
   <p class="alt__para">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem, quibusdam!</p>
</body>
<!--Body ends here-->
</html>

To build a project, we need to use different kinds of html tags to make it successful. In the same way, I have also used many different html tags in my different projects.

Some of them are:

  • <p>: Paragraph is a block level tag used to create paragraphs in html project. It takes the whole area both in the left and in the right as it’s a block level tag.
  • <span>: Span is an inline text element. It has styling by default. So if we write something inside the span element styling is done by default.
  • <strong>: To display anything in bold we can use <strong> tag.
  • <h1>Header: There are different levels of headers used to build a project like <h1>,<h2>,<h3>,<h4>,<h5> etc.
  • <div>: It’s actually a container element. It does not have any styling by default and also its a block level element.
  • <i>: Through this <i> tag we can display anything in italics in the HTML project.
  • <br>: It is used to give a line break in the code. As in HTML space does not display break. So to give a break we need to use the tag <br>.
  • <ul>: In HTML, we can display a list both in order as well as unordered way. When the list is not in order, we use the tag <ul>.
  • <ol>: Through the above statement we have come to know that to display something in an unordered way we use the tag <ul>. In the same way, to make an ordered list we use <ol> in HTML.
  • <li>:  It is used for listing the items inside the <ul> and <ol> tags. For each list items separate <li> is used which is denoted by any symbol or numbers.
  • <table>: For building a table inside the project we use the tag <table>. We generally write related data inside a table.
  • <tr>: Table row is used to create table rows in <table> tag.
  • <td>: Table cells are defined through table data which in turn is also inside the table element.
  • <tbody>: It is an optional element inside a table tag. Generally used to group all the rows which are not in <thead> tag.
  • <section>: Section is like div tag which is used to create a specific section in the HTML project.
  • <nav>: Through <nav> tag we can create navigation link of the page. This helps the user to navigate through the page.
  • <img>: To display image in the page we use the <img> tag. Image tag also requires <src> source tag as well as < alt> tag to display any image in the page.
  • <video>: We can also embed video in our html page with the help of <video> tag. We can embed any kind of video like a music video or a game video etc. through this tag.
  • <audio>: We can embed sound files in our web page through this <audio> tag.
  • <form>: For building a form in the web page the <form> tag is used. Inside the form tag, you can create checkbox, radio button, text fields, etc. In the end, a form contains a submit button so that the user can input the required data and submit it.
  • <input>: It is used inside a form to take input from the user. With the type attribute, it takes different forms like text, radio, checkbox, password, date, number. It is one of the most common tags used on the web.
  • <textarea>: It is also used inside a form to take input from the user. It is like <input type=“text”> but it is generally used for multiline inputs. It is useful when you want to take more input from the user.
  • <label>: It is associated with the <input> tag and used with it. Although not required and we can use simple text with <input> also. But, it is programmatically associated with <input> tag and also used by screen readers.
  • <select>: It is the dropdown, which we find in almost any form. There can be many items in a select tag.
  • <option>: It is used with the select tag to define the individual items inside it.

To group related information together list is used in HTML.

There are three types of lists namely <ul> unordered list, <ol> ordered list. All the items in any type of list will be defined by <li> tag.

  • <ul> unordered list: This is the type of list which is not ordered i.e its not listed in numbers. It is displayed by using bullets or any other special character.

Unordered list can also have an attribute type. It specifies the type of bullet you will have, default is a disc.

<!DOCTYPE html>
<html>
<head>
   <title>Unordered list tutorials</title>
</head>
<body>
   <h2>Unordered list - 1</h2>
   <ul>
       <li>Pumpkin</li>
       <li>Tomato</li>
       <li>Potato</li>
       <li>Onion</li>
   </ul>
   <h2>Unordered list - 2</h2>
   <ul type="square">
       <li>Tiger</li>
       <li>Lion</li>
       <li>Goat</li>
       <li>Horse</li>
   </ul>
   <h2>Unordered list - 3</h2>
   <ul type="circle">
       <li>Car</li>
       <li>Bike</li>
       <li>Boat</li>
       <li>Tank</li>
   </ul>
</body>
</html>

<ul> unordered list

  • <ol> Ordered List: 

Ordered list is listed with numbers i.e it has a sequence. An ordered list can also have an attribute type. It specifies the type of numbering you will have, default is Numbers. It can also have upper case roman, lower case roman, upper case letters, and lower-case letters. It also has an attribute start, which defines the number/alphabet the numbering will start.

All of these are in the below example.

<!DOCTYPE html>
<html>
<head>
   <title>Ordered list tutorials</title>
</head>
<body>
   <h2>Ordered list - 1</h2>
   <ol>
       <li>Pumpkin</li>
       <li>Tomato</li>
       <li>Potato</li>
       <li>Onion</li>
   </ol>
   <h2>Ordered list - 2</h2>
   <ol type="I">
       <li>Tiger</li>
       <li>Lion</li>
       <li>Goat</li>
       <li>Horse</li>
   </ol>
   <h2>Ordered list - 3</h2>
   <ol type="i" start = "4">
       <li>Car</li>
       <li>Bike</li>
       <li>Boat</li>
       <li>Tank</li>
   </ol>
   <h2>Ordered list - 4</h2>
   <ol type="a">
       <li>Red</li>
       <li>Green</li>
       <li>Blue</li>
       <li>Yellow</li>
   </ol>
   <h2>Ordered list - 5</h2>
   <ol type="A" start = "7">
       <li>Engineer</li>
       <li>Accountant</li>
       <li>Doctor</li>
       <li>Coder</li>
   </ol>
</body>
</html>

<ol> Ordered List

Html table tag helps us to arrange our item in rows and columns of cells. To create HTML table we use <table> tag and along with this, we need to use <tr> tag which creates rows in the table and <td>  tag through which we can input data inside our table. To put heading inside the table we can use <th> tag which helps to give heading to the table.

There are also two optional tags called <thead> and <tbody>, which are used to group header and body respectively.

We can also combine any row, with the colspan attribute. One more thing to note is that earlier there were many more attributes to style the table. But with HTML5 specifications, we need to style a table through CSS.

In the below example, we can see a simple table and other tables with all tags.

<!DOCTYPE html>
<html>
<head>
   <title>Table tutorials</title>
   <style>
       table,
       td {
           border: 1px solid #333;
       }
       thead,
       tfoot {
           background-color:lightslategray;
           color: #fff;
       }
   </style>
</head>
<body>
   <h1>Simple table</h1>
   <table>
       <tr>
           <th>First name</th>
           <th>Last name</th>
       </tr>
       <tr>
           <td>John</td>
           <td>Wayne</td>
       </tr>
       <tr>
           <td>Tommy</td>
           <td>Lee</td>
       </tr>
   </table>
   <h1>Table with thead, tfoot, and tbody</h2>
       <table>
           <thead>
               <tr>
                   <th>Countries</th>
                   <th>Population</th>
               </tr>
           </thead>
           <tbody>
               <tr>
                   <td>India</td>
                   <td>1.32 Billion</td>
               </tr>
               <tr>
                   <td>China</td>
                   <td>1.38 Billion</td>
               </tr>
           </tbody>
           <tfoot>
               <tr>
                   <td colspan="2">Largest Population</td>
               </tr>
           </tfoot>
       </table>
</body>
</html>

HTML Table

To embed any kind of video in the web page, <video> tag is used. We need to use <source> tag inside the <video> tag to specify which file to upload. It will then contains the src attribute. Any kind of video could be uploaded like a song video, or a short story video or an educational video, etc.

The important thing to note is that the video needs to be there on your web-server, or in your local drive if testing locally.

There are many attributes to the video tag like controls, autoplay, muted, loop.

  • controls will show a basic youtube like control buttons in the media player.
  • autoplay will begin the play as soon as the page is loaded.
  • muted will play the video without volume.
  • loop will play the video in the loop and will run forever.
<!DOCTYPE html>
<html>
<head>
   <title>Video Demo</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
   <div class="grid__iframe">
       <video controls autoplay muted loop>
           <source src="flower.mp4" type="video/mp4">
           <source src="flower.webm" type="video/webm">
           <p>Your browser doesn't support HTML5 video.</p>
       </video>
   </div>
</body>
</html>

For the above to work, you should have a flower.webm or flower.mp4 in the same directory as demo.html flower.mp4 as demo.html

Just like <video> we can also embed any kind of audio in a web page using <audio> tag. Any type of sound can be embedded in the web page starting from music to any kind of educational audio. Currently, three types of file formats are supported by <audio> element namely MP3, WAV and OCG.

The important thing to note is that the audio need to be there on your web-server, or in your local drive if testing locally.

The attributes are similar to the video tag and are controls, autoplay, muted, loop.

  • controls will show controls in the media player.
  • autoplay will begin the play as soon as the page is loaded.
  • muted will play the audio without volume. Not recommended
  • loop will play the audio in loop and will run forever.
<!DOCTYPE html>
<html>
<head>
   <title>Audio Demo</title>
   <style>
       .grid__iframe {
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
   <div class="grid__iframe">
       <audio controls autoplay loop>
           <source src="t-rex-roar.mp3" type="audio/mpeg">
           <source src="t-rex-roar.ogg" type="audio/ogg">
           <p>Your browser doesn't support HTML5 audio.</p>
           </audio>
   </div>
</body>
</html>

On the above, you should have a t-rex-roar.mp3 or t-rex-roar.ogg in the same directory as audio.html t-rex-roar.mp3 as audio.html

We can create links to sections within the same page, using id tag in that part of the webpage. And then in <a> tag in href we mention that id by #id_name.

This type of layout is very common nowadays because of Single Page Websites, where all the information is generally is on one page only.

In the following example, we are creating <nav> links on clicking of which it will take us to respective sections.

<!DOCTYPE html>
<html>
<style>
nav{
   background: yellow;
   padding: 2%;
   font-size:1.2rem;
}
footer{
   background: yellow;
   padding: 1%;
   font-size:1rem;
}
main, header{
text-align: center;
}
</style>
<body>
    <nav>
        <a href="#about__chrome">Chrome</a> |
        <a href="#about__firefox">Firefox</a> |
        <a href="#about__safari">Safari</a> |
        <a href="#about__explorer">Internet Explorer</a>
    </nav>
   <header>
       <h1>Web Browsers</h1>
       <p>Google Chrome and Firefox are the most used browsers today.</p>
       <hr>
   </header>
   <main>
       <article id="about__chrome">
           <section>
               <h1>Google Chrome</h1>
               <p>Google Chrome is a free, open-source web browser developed by Google, released in 2008.</p>
               <figure>
                   <img src="https://source.unsplash.com/900x600/?nature" width="100%" alt="Nature">
                   <figcaption>Random Nature image</figcaption>
               </figure>
           </section>
           <section>
               <h2>More Information</h2>
               <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                   Unde consequatur doloremque reiciendis saepe! Iure dicta
                   harum molestias laborum accusantium reprehenderit
                   sunt, repudiandae eos aut itaque dolores et repellendus.
                   Dignissimos, voluptate.
               </p>
               <hr>
           </section>
       </article>
       <article id="about__firefox">
           <section>
               <h1>Mozilla Firefox</h1>
               <p>Firefox is a free, open-source web browser from Mozilla, released in 2004.</p>
               <figure>
                   <img src="https://source.unsplash.com/900x600/?water" width="100%" alt="Water">
                   <figcaption>Random Water image.</figcaption>
               </figure>
           </section>
           <section>
               <h2>More Information</h2>
               <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                   Unde consequatur doloremque reiciendis saepe! Iure dicta
                   harum molestias laborum accusantium reprehenderit
                   sunt, repudiandae eos aut itaque dolores et repellendus.
                   Dignissimos, voluptate.
               </p>
           </section>
       </article>
       <article id="about__safari">
               <section>
                   <h1>Safari</h1>
                   <p>GSafari is a graphical web browser developed by Apple, based on the WebKit engine.</p>
                   <figure>
                       <img src="https://source.unsplash.com/900x600/?nature" width="100%" alt="Nature">
                       <figcaption>Random Nature image</figcaption>
                   </figure>
               </section>
               <section>
                   <h2>More Information</h2>
                   <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                       Unde consequatur doloremque reiciendis saepe! Iure dicta
                       harum molestias laborum accusantium reprehenderit
                       sunt, repudiandae eos aut itaque dolores et repellendus.
                       Dignissimos, voluptate.
                   </p>
                   <hr>
               </section>
           </article>
           <article id="about__explorer">
               <section>
                   <h1>Internet Explorer</h1>
                   <p>Internet Explorer[a] (formerly Microsoft Internet Explorer[b] and Windows Internet
                       Explorer,[c] commonly abbreviated IE or MSIE) was a series of graphical web browsers
                       (or as of 2019, a "compatibility solution"[5]) developed by Microsoft and
                       included in the Microsoft Windows line of operating systems, starting in 1995.</p>
                   <figure>
                       <img src="https://source.unsplash.com/900x600/?water" width="100%" alt="Water">
                       <figcaption>Random Water image.</figcaption>
                   </figure>
               </section>
               <section>
                   <h2>More Information</h2>
                   <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                       Unde consequatur doloremque reiciendis saepe! Iure dicta
                       harum molestias laborum accusantium reprehenderit
                       sunt, repudiandae eos aut itaque dolores et repellendus.
                       Dignissimos, voluptate.
                   </p>
               </section>
           </article>
   </main>
</body>
</html>

Web browsers

HTML5 have sampled the syntax and structure of the HTML document.
Earlier version of HTML ie HTML4.01 had a very cumbersome DOCTYPE and also the charset declared in the head tag. These have been simplified a lot in HTML5.

HTML5 syntax

<!DOCTYPE html>
<html>
<head>
...
<meta charset="UTF-8">
...
</head>
...
</html>

HTML4.01 syntax

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
   ...
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   ...
 </head>
 ...
</html>

In HTML5 the Geolocation API was introduced. With the help of it, we can get the user location very easily through a browser.

We can get the current position of the user through the navigator.geolocation.getCurrentPosition() method.

It takes one required and two optional arguments. The required argument is the success argument and the optional ones are an error, options.

  • success - The main callback function to show our coordinates. Only we have access to Position object, from which we can take latitude and longitude of the user
  • error - An optional callback function, which will show the error message in case of any error.
  • options- An optional object in which we can give enableHighAccuracy, timeout, and maximumAge.
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Geolocation Demo</title>
   <script>
   window.onload = function () {
       var options = {
           enableHighAccuracy: true,
           timeout: 5000,
           maximumAge: 0
       };
       function success(pos) {
           let loc = document.getElementById("my_location");
           var crd = pos.coords;
           loc.innerHTML = `Latitude : ${crd.latitude}, Longitude: ${crd.longitude}, More or less ${crd.accuracy} meters.`;
       }
       function error(err) {
           let loc = document.getElementById("my_location");
           loc.innerHTML = `ERROR(${err.code}): ${err.message}`;
       }
       navigator.geolocation.getCurrentPosition(success, error, options);
   };
   </script>
</head>
<body>
   <h1>Geolocation Demo</h1>
   <p>Grant permissions to know your location.</p>
   <p>Your current position is:</p>
   <div id="my_location"></div>
</body>
</html>

Geolocation Demo

Open this file in the browser and you will get a pop-up, asking to Allow to use current location.

Geolocation Demo

Click on “Allow” and you will get your current location.

Close and open the demo.html again. This time click on “Don’t Allow” and you will get the error message which has been shown by the error function.

Geolocation Demo

  • <datalist> tag is like the dropdown tag of <select>. It contains a set of <option> tag inside it to repress the value. It is a bit different in representation from the Dropdown. It is like a plain text box. Once you click inside the text box, it will show the complete list. Or if you type it will show the filtered list.
  • <output> tag represents the result of some operation, performed by our form.

In our example, the <datalist> tag operation is straightforward as, it is used to select a list of browsers. Then there is a <input type=“range”> slider in our code. Once we slide it the value of it is processed and shown in our <output> tag.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Datalist and output</title>
   <style>
       form{
           display: grid;
           place-content: center;
           grid-gap: 10px;
           border: 1px solid black;
       }
       label {
           font-family: "Fira Sans", sans-serif;
       }
   </style>
</head>
<body>
   <form oninput="ratings.value = parseInt(z1.value)">
   <h1>Datalist & Output Demo</h1>
       <div>
           <label for="myBrowser">Choose a browser from this list:</label>
           <input list="browsers" id="myBrowser" name="myBrowser" />
           <datalist id="browsers">
               <option value="Chrome">
               <option value="Firefox">
               <option value="Internet Explorer">
               <option value="Opera">
               <option value="Safari">
               <option value="Microsoft Edge">
           </datalist>
       </div>
       <div>
           <label for="browserRating">Give a Rating for your browser:</label>
           <input id="browserRating" type="range" name="z1" value="0" />
       </div>
       <div>
           <label for="myRatings">My Ratings:</label>
           <output id="myRatings" name="ratings"></output>
       </div>
   </form>
</body>
</html>

Datalist & output demo

Selecting the <datalist> On changing the rating

Datalist & output demo

<input> tag is the tag which creates fields inside the <form> tag for the website visitor to enter his/her information accordingly. There are different types of input available to the developer to use, to get the user input.

As per standard practice the <input> tags, should have a <label> tag. And the for attribute in a label should match the id attribute in the input.

So, the different types are -

  • <input type=“text”> - The most common of the types, which produces a simple text box in which the user can type anything - numbers, alphabets.
  • <input type=“radio”> - The input element of type radio are mostly used in groups. Only one radio button from the group is selected at a time. They are by default rendered as a small circle, which are filled once selected.
  • <input type=“checkbox”> - The input element of type checkbox, are mostly are by default rendered as square boxes. We can select all of them or some of them.
  • <input type=“password”> - The input element of type password, is used to enter secure text. It is basically like a type text, but whatever you enter will be marked by an asterisk(“*”).
  • <input type=“file”> - The input element with type=“file”, let the user choose one or more file from their computer. These files can then be uploaded to a server when we submit the form.
  • <input type=“hidden”> - The input element with type=“hidden”, is basically used by the web developer. It is mainly used to pass some security token when submitting the form.
  • <input type=“image”> - The input element with type=“image”, is used to create a graphical submit button. It is to be noted that you should have an image of a button, for this to work.
  • <input type=“button”> - The input element with type=“button”, is a plain button which we have to program to do something.
  • <input type=“reset”> - The input element with type=“reset”, are rendered as button. On clicking this type of button, it will remove all the data, which we have entered in our form.
  • <input type=“submit”> - The input element with type=“submit”, are rendered as a button. On click of these type of button, it will take are entered value in the form and will try to submit to the server.

We will use all of these above types to create our example.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Datalist and output</title>
   <style>
       form{
           display: grid;
           place-content: center;
           grid-gap: 10px;
           border: 1px solid black;
       }
       label {
           font-family: "Fira Sans", sans-serif;
       }
       input[type='image'] {
           width: 120px;
       }
       input[type='reset'],
       input[type='button'] {
           border: 0;
           line-height: 2.5;
           padding: 0 20px;
           font-size: 1rem;
           text-align: center;
           color: #fff;
           text-shadow: 1px 1px 1px #000;
           border-radius: 10px;
           background-color: lightskyblue;
           cursor: pointer;
       }
       .styled {
           border: 0;
           line-height: 2.5;
           padding: 0 20px;
           font-size: 1rem;
           text-align: center;
           color: #fff;
           text-shadow: 1px 1px 1px #000;
           border-radius: 10px;
           background-color: rgba(220, 0, 0, 1);
           cursor: pointer;
       }
       .styled:hover {
           background-color: rgba(255, 0, 0, 1);
       }
       #button_eg{
           display: flex;
           justify-content: center;
           align-items: center;
       }
   </style>
</head>
<body>
   <form>
       <h1>Input Type Demo</h1>
       <div id="text_eg">
           <label for="name">Enter Name ( 4 to 12 characters ) :</label>
           <input type="text" id="name" name="name" required minlength="4" maxlength="12" size="20">
       </div>
       <div id="password_eg">
           <label for="pass">Password (8 characters minimum):</label>
           <input type="password" id="pass" name="password" minlength="8" required>
       </div>
       <div id="img_eg">
           <label for="avatar">Choose a profile picture:</label>
           <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
       </div>
       <div id="radio_eg">
           <label>Gender:</label>
           <div>
               <input type="radio" id="male" name="gender" value="male" checked>
               <label for="male">Male</label>
           </div>
           <div>
               <input type="radio" id="female" name="gender" value="female">
               <label for="female">Female</label>
           </div>
           <div>
               <input type="radio" id="unknown" name="gender" value="unknown">
               <label for="unknown">Not Specified</label>
           </div>
       </div>
       <div id="checkbox_eg">
           <label>Choose your hobbies:</label>
           <div>
               <input type="checkbox" id="code" name="code" checked>
               <label for="code">Coding</label>
           </div>
           <div>
               <input type="checkbox" id="travel" name="travel">
               <label for="travel">Travelling</label>
           </div>
           <div>
               <input type="checkbox" id="movies" name="movies">
               <label for="movies">Movies</label>
           </div>
       </div>
       <div id="hidden_eg">
           <input id="prodId" name="prodId" type="hidden" value="xm234jq">
       </div>
       <div id="button_eg">
           <input type="image" id="image" alt="Login" src="login-button.png">
           <input type="button" value="Click Me">
           <input type="reset" value="Reset">
           <input class="styled" type="submit" value="Send Request">
       </div>
   </form>
</body>
</html>

Input Type Demo

There are many new input types introduced in HTML5. These are in addition to the one we have seen in Question 25.

So, the new types are -

  • <input type=“color”> - The input element with type=“color”, let the user select a color from a color palette. The different browser shows a different color palette.
  • <input type=“date”> - The input element with type=“date”, let the user select a date from a calendar pop-up or input it himself. The different browser shows a different date pop-up.
  • <input type=“datetime-local”> - The input element with type=“datetime-local”, let the user select both date and time from a pop-up and he can also input it in the text box.
  • <input type=“email”> - The input element with type=“email”, let the user enter his email. The input entered is automatically validated to contain a valid email.
  • <input type=“month”> - The input element with type=“month”, let the user enter a month and a year. The value entered is in the format YYYY-MM.
  • <input type=“time”> - The input element with type=“time”, let the user enter time in an hour, minutes and seconds.
  • <input type=“url”> - The input element with type=“url”, let the user enter a URL. The input entered is automatically validated to contain a valid URL.
  • <input type=“number”> - The input element with type=“number”, let the user enter number. He/She can enter the number in the text-box or also can increase/decrease it with the provided counter.
  • <input type=“range”> - The input element with type=“range”, let the user specify a numeric value with a graphical slider.
  • <input type=“search”> - The input element with type=“search”, is a specially designed text field. It allows the user to enter the search term into it.
  • <input type=“tel”> - The input element with type=“tel”, let the user enter a telephone number. Unlike <input type=“email”> the input is not automatically validated and we have to use pattern.

We will use all the above to create our example.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Input types</title>
   <style>
       h1{
           text-align: center;
       }
       form{
           display: grid;
           place-content: center;
           grid-gap: 10px;
           border: 1px solid black;
       }
       form > * {
           display: grid;
           grid-template-columns: 150px 1fr;
           place-content: center;
       }
       label {
           font-family: "Fira Sans", sans-serif;
       }
   </style>
</head>
<body>
   <h1>HTML5 Input Types Demo</h1>
   <form>
       <div id="search_eg">
           <label for="site-search">Search the site:</label>
           <input type="search" id="site-search" name="q" aria-label="Search through site content">
       </div>
       <div id="time_eg">
           <label for="appt">Choose a time:</label>
           <input type="time" id="appt" name="appt" min="9:00" max="18:00" required>
       </div>
       <div id="url_eg">
           <label for="url">Enter an URL:</label>
           <input type="url" name="url" id="url" placeholder="https://example.com" pattern="https://.*" size="30"
               required>
       </div>
       <div id="phone_eg">
           <label for="phone">Enter your phone:</label>
           <input type="tel" id="phone" name="phone" placeholder="123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
       </div>
       <div id="month_eg">
           <label for="month">Enter a month:</label>
           <input type="month" id="month" name="month" min="2018-03" value="2019-05">
       </div>
       <div id="email_eg">
           <label for="email">Enter your email:</label>
           <input type="email" id="email" pattern=".+@gmail.com" size="30" required>
       </div>
       <div id="number_eg">
           <label for="tentacles">Enter a number:</label>
           <input type="number" id="tentacles" name="tentacles" min="10" max="100">
       </div>
       <div id="range_eg">
           <label for="volume">Choose a Range:</label>
           <input type="range" id="start" name="volume" min="0" max="11">
       </div>
       <div id="color_eg">
           <label for="favorite">Choose a color:</label>
           <input type="color" id="favorite" name="favorite" value="#e66465">
       </div>
       <div id="date_eg">
           <label for="date">Select a date:</label>
           <input type="date" id="date" name="date-start" value="2019-04-22" min="2018-01-01" max="2025-12-31">
       </div>
       <div id="datetime_eg">
           <label for="appointment-time">Choose a time:</label>
           <input type="datetime-local" id="appointment-time" name="appointment-time" value="2019-04-12T19:30" min="2019-04-07T00:00"
               max="2025-06-14T00:00">
       </div>
   </form>
</body>
</html>

HTML5 input type demo

We create drop-down in HTML using the <select> tag. The different values in the <select> tag are entered using a set of <option> tag. Each <option> tag have a value attribute and this only gets chosen when we select an option.

A simple drop-down example is below.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>DropDown</title>
   <style>
       h1 {
           text-align: center;
       }
       form {
           display: grid;
           place-content: center;
           grid-gap: 10px;
           border: 1px solid black;
       }
       label {
           font-family: "Fira Sans", sans-serif;
       }
   </style>
</head>
<body>
   <h1>Drop-down Demo</h1>
   <form>
       <label for="profession-select">Choose Your Profession:</label>
       <select id="profession-select">
           <option value="">--Please choose an option--</option>
           <option value="engineer">Engineer</option>
           <option value="doctor">Doctor</option>
           <option value="developer">Developer</option>
           <option value="architect">Architect</option>
           <option value="chef">Chef</option>
           <option value="manager">Manager</option>
       </select>
   </form>
</body>
</html>

Drop-down Demo

The HTML and CSS standards are decided by W3C - World Wide Web Consortium. It is this non-government organisation which create rules, and the browser creators(google, mozilla, apple, Microsoft) have to follow them.

Although they follow the W3C standard, they are not bound to follow completely. Besides, each of these browsers was created using a different layout and Javascript engines, so they behave differently.

  • Firefox uses Gecko (now Quantum), IE uses Trident, Chrome and Safari use Webkit as layout engines.
  • Similarly, Chrome uses V8, IE uses Chakra and FireFox uses Spidermonkey as their JavaScript engine.

The HTML5 standard, which was recommended in 2014 still is now standardised across browsers. The HTML5 input tags behave differently, with some browsers not even supporting some of them.

We will use the below code, to check the browser differences.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Difference</title>
   <style>
       h1 {
           text-align: center;
       }
       form {
           display: grid;
           place-content: center;
           grid-gap: 10px;
           border: 1px solid black;
       }
       form > * {
           display: grid;
           grid-template-columns: 180px 1fr;
           place-content: center;
       }
       label {
           font-family: "Fira Sans", sans-serif;
       }
       #button_eg,#checkbox_eg,#radio_eg{
           display: flex;
           justify-content: center;
           align-items: center;
       }
       input[type='image'] {
           width: 80px;
       }
   </style>
</head>
<body>
   <h1>Browser Differences</h1>
   <form>
           <div id="search_eg">
                   <label for="site-search">Search the site:</label>
                   <input type="search" id="site-search" name="q" aria-label="Search through site content">
               </div>
               <div id="time_eg">
                   <label for="appt">Choose a time:</label>
                   <input type="time" id="appt" name="appt" min="9:00" max="18:00" required>
               </div>
               <div id="url_eg">
                   <label for="url">Enter an URL:</label>
                   <input type="url" name="url" id="url" placeholder="https://example.com" pattern="https://.*" size="30"
                       required>
               </div>
               <div id="phone_eg">
                   <label for="phone">Enter your phone:</label>
                   <input type="tel" id="phone" name="phone" placeholder="123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
               </div>
               <div id="month_eg">
                   <label for="month">Enter a month:</label>
                   <input type="month" id="month" name="month" min="2018-03" value="2019-05">
               </div>
               <div id="email_eg">
                   <label for="email">Enter your email:</label>
                   <input type="email" id="email" pattern=".+@gmail.com" size="30" required>
               </div>
               <div id="number_eg">
                   <label for="tentacles">Enter a number:</label>
                   <input type="number" id="tentacles" name="tentacles" min="10" max="100">
               </div>
               <div id="range_eg">
                   <label for="volume">Choose a Range:</label>
                   <input type="range" id="start" name="volume" min="0" max="11">
               </div>
               <div id="color_eg">
                   <label for="favorite">Choose a color:</label>
                   <input type="color" id="favorite" name="favorite" value="#e66465">
               </div>
               <div id="date_eg">
                   <label for="date">Select a date:</label>
                   <input type="date" id="date" name="date-start" value="2019-04-22" min="2018-01-01" max="2025-12-31">
               </div>
               <div id="datetime_eg">
                   <label for="appointment-time">Choose a time:</label>
                   <input type="datetime-local" id="appointment-time" name="appointment-time" value="2019-04-12T19:30" min="2019-04-07T00:00"
                       max="2025-06-14T00:00">
               </div>
       <div id="option_eg">
               <label for="profession-select">Choose Your Profession:</label>
               <select id="profession-select">
                   <option value="">--Please choose an option--</option>
                   <option value="engineer">Engineer</option>
                   <option value="doctor">Doctor</option>
                   <option value="developer">Developer</option>
                   <option value="architect">Architect</option>
                   <option value="chef">Chef</option>
                   <option value="manager">Manager</option>
               </select>
       </div>
       <div id="text_eg">
               <label for="name">Enter your Name:</label>
               <input type="text" id="name" name="name" required minlength="4" maxlength="12" size="20">
           </div>
           <div id="password_eg">
               <label for="pass">Enter Password:</label>
               <input type="password" id="pass" name="password" minlength="8" required>
           </div>
           <div id="img_eg">
               <label for="avatar">Choose a profile picture:</label>
               <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
           </div>
           <div id="radio_eg">
               <label>Gender:</label>
               <div>
                   <input type="radio" id="male" name="gender" value="male" checked>
                   <label for="male">Male</label>
               </div>
               <div>
                   <input type="radio" id="female" name="gender" value="female">
                   <label for="female">Female</label>
               </div>
               <div>
                   <input type="radio" id="unknown" name="gender" value="unknown">
                   <label for="unknown">Not Specified</label>
               </div>
           </div>
           <div id="checkbox_eg">
               <label>Choose your hobbies:</label>
               <div>
                   <input type="checkbox" id="code" name="code" checked>
                   <label for="code">Coding</label>
               </div>
               <div>
                   <input type="checkbox" id="travel" name="travel">
                   <label for="travel">Travelling</label>
               </div>
               <div>
                   <input type="checkbox" id="movies" name="movies">
                   <label for="movies">Movies</label>
               </div>
           </div>
           <div id="hidden_eg">
               <input id="prodId" name="prodId" type="hidden" value="xm234jq">
           </div>
           <div id="button_eg">
               <input type="image" id="image" alt="Login" src="login-button.png">
               <input type="button" value="Click Me">
               <input type="reset" value="Reset">
               <input class="styled" type="submit" value="Send Request">
           </div>
   </form>
</body>
</html>

In the case of Safari, the type of month, color, date, and datetime-local are all plain text box because they are not supported.

Browser Differences

Browser Differences

In the case of Firefox, the type of month and datetime-local are all plain text box because they are not supported. The type of color, date are supported by Firefox.
In case of chrome, everything is supported.

Browser Differences

Browser Differences

In the case of Internet Explorer 11, the layout even is weird because of poor support for the current implementation of the grid and also missing support for input types month, color, date, and datetime-local.

In the case of Edge, the grid support is there but in a different way. But it supports all input types month, color, date and datetime-local, although the display is different.

Browser Differences

SVG or Scalable Vector Graphics is a mark-up language for creating beautiful, 2-D graphics. SVG is open sourced and designed to work with other web standards like CSS and DOM.

We can draw different shapes with ease with sag like circle, rectangle, ellipse, polygon and also various other effects.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>SVG Demo</title>
   <style>
       .grid__svg {
           display: grid;
           place-content: center;
       }
   </style>
</head>
<body>
   <div class="grid__svg">
       <h4>SVG Demo</h4>
       <div class="circle">
           <svg width="100" height="100">
               <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
           </svg>
       </div>
       <div class="rectangle">
           <svg width="400" height="110">
               <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
           </svg>
       </div>
       <div class="ellipse">
           <svg height="140" width="500">
               <ellipse cx="110" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2" />
           </svg>
       </div>
       <div class="line">
           <svg height="210" width="500">
               <line x1="0" y1="0" x2="150" y2="150" style="stroke:rgb(255,0,0);stroke-width:2" />
           </svg>
       </div>
       <div class="polygon">
           <svg height="210" width="500">
               <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" />
           </svg>

SVG demo

</div>
   </div>
</body>
</html>

The HTML5 Web worker was made to make the web asynchronous. We all know that JavaScript is single threaded. It will stop the execution of the web-browser, till a script is completed and will not proceed further.

Sometimes, it is not desirable. We want to show our visitor the website and let the heavy script which might be fetching big data from an API run in the background and complete. In these situations, web workers come to the rescue.

Web workers are initialized using var worker = new Worker(‘extremeLoop.js');

Here, extremeLoop.js is our computationally heavy JavaScript file which we want to run separately. Once the Web Worker is started, communication between a web worker and its parent is generally done using the postMessage() method.

Then the message is passed by Web Worker to the main page using onmessage event.

Here in the example, we have a simple web worker to calculate the prime.

<!DOCTYPE HTML>
<html>
<head>
 <meta charset="utf-8">
 <title>Web Worker example</title>
</head>
<body>
 <p>The highest prime number discovered so far is: <output id="result"></output></p>
 <script>
  var worker = new Worker('extremeLoop.js');
  worker.onmessage = function (event) {
    document.getElementById('result').textContent = event.data;
  };
 </script>
</body>
</html>

Save the JavaScript file in the same directory as  extremeLoop.js

var n = 1;
search: while (true) {
 n += 1;
 for (var i = 2; i <= Math.sqrt(n); i += 1)
   if (n % i == 0)
    continue search;
 postMessage(n);
}

Now, open the browser and you will get.

Web workers

DESCRIPTION

HTML is known as Hypertext Markup Language and the standard markup language used to create web pages and web applications. HTML, along with Cascading Style Sheets (CSS) and JavaScript, forms a foundation for technologies related to the World Wide Web.

HTML is free, easy to understand and use. Its syntax is quite similar to XML’s and is supported by most web development tools, not to forget that It is the most user-friendly programming language.

Moreover, it is supported by nearly all the available browsers. No other programming language is as compatible with browsers as HTML. Due to this, any web page in the HTML format can be optimized easily and will open in almost all browsers throughout the world. To learn more about HTML, you can enroll with us in our HTML course to have more knowledge and prepare better for the interview. 

As a fresher in web development, one starts as an entry-level Web Developer, designing and creating websites for the client.

You may work as a Back-end Web Developer, where you will do the heavy lifting to maintain the overall technical construction of websites. You will be required to create the basic framework of the site with full expected functionality and make arrangements and changes to allow others to make changes to the website and discuss with the management about the same.

The next option is working as a Front-end Web Developer, where you will determine the looks of a website by creating the layout of the site and combining graphics, applications, and other content, not to forget writing web design programs in many computer languages like HTML or JavaScript.

Then you have the Webmasters job position, where you will ensure that the websites are properly maintained and updated, testing them for errors like broken links to ensure maximum functionality and often responding to user comments too.

According to payscale.com, the average salary for entry-level HTML Developers is $73,619, going as high as $106,468 per annum, while for experienced HTML Developers, the average salary is 96,364, going as high as $129,181 per annum. The primary companies hiring HTML developers are IBM, Microsoft Corp, HP, Google, Intel, Apple Inc, and Amazon.com Inc.

There are a host of opportunities in the world of web development for a skilled HTML Developer. All you need to crack an HTML interview is a systematic approach to prepare for the questions and answers that will help you deal with the tricky situation in the interview sessions. As we are well versed in the various difficult scenarios, our 30 HTML interview questions and answers will pack a punch to successfully crack your HTML interviews. This set of HTML questions and answers will help the freshers and prove very helpful for experienced HTML developers looking for better prospects in their line of work. Additionally, this will help you get an edge over others to get your dream HTML Developer job that you have been yearning for. To delve into more courses and upskill your career, you can join our programming training courses. 

So, why wait any longer? Go at our HTML interview questions, crack any HTML job interview, and land your dream job!

Read More
Levels