This article covers the most common HTML and HTML5 questions in interviews.
Introduce:
Before we get into the interview questions in the HTML language, let’s first understand HTML, what HTML is, the employment opportunities it provides, and so on.
HTML stands for Hypertext Markup Language. It is a standard text formatting language published in 1993 for the development of web pages. HTML is a language that is interpreted by the browser and tells the browser what to display and how.
If someone wants to work in the field of web development [web designer, web developer], then HTML is an important language to learn. For web developers, HTML alone is not enough, because HTML only defines the structure of the data that will be rendered on the browser in the web page, and in order to make it visually appealing and make it functional, we need to use CSS and Javascript respectively.
The latest version of HTML is HTML5. There are two main components in the HTML language, tags and attributes. The following diagram shows some basic HTML tags and attributes.
HTML Common Interview Questions and Answers Collection
HTML Are tags and elements the same thing?
No. An HTML element is defined by a starting tag and may contain some content and an ending tag. For example, <h1>Heading 1</h1> is an HTML element, but only <h1> is the starting tag and </h1> is a closing tag.
What are the tags and attributes in HTML?
Tags are the main component of HTML that defines the structure/formatting of the content, while attributes are used in conjunction with HTML tags to define the characteristics of an element. For example, <p align=”center” > interview question </p>, where “align” is the property we use to align paragraphs to appear in the center of the view.
What are HTML common interview questions: What is the void element in HTML?
HTML elements that don’t have a closing tag or don’t need to be closed are void elements. For example< br />, < img />, <hr />, etc. You can download a PDF version of the HTML interview questions.
What are the benefits of folding blanks?
In HTML, a blank sequence of whitespace characters is treated as a single whitespace character because the browser collapses multiple spaces into a single whitespace character, which helps developers indent lines of text without worrying about multiple spaces and keep the HTML readable and intelligible code.
What is an HTML entity?
HTML Interview Question Analysis: In HTML, some characters are retained, such as “<“, “>”, “/”, etc. To use these characters in our web pages, we need to use a character entity called an HTML entity. Here are some mappings between reserved characters and their respective entity characters to use.
character | Entity name | Entity number |
---|---|---|
< | < | < |
> | > | > |
& | & | & |
(non-stop space) Eg. 10 PM | Eg. <p>10  PM</p> |
What are the different types of listings in HTML?
What is the “class” property in HTML?
The class attribute is used to specify the class name of an HTML element. Multiple elements in HTML can have the same class value. In addition, it is mainly used to associate styles written in stylesheets with HTML elements.
What is the difference between the ‘id’ attribute and the ‘class’ attribute of a HTML element?
Multiple elements in HTML can have the same class value, while the id attribute value of one element cannot be associated with another HTML element.
Define multi-part form data?
Multipart form data is one of the values of the enctype property. It is used to send file data to the server side for processing. Other valid values for the enctype attribute are text/plain and application/x-www-form-urlencoded.
Describe the HTML layout structure.
Each web page has different components to display the intended content and a specific UI. However, there are still some things that are templated and are globally accepted ways of building web pages, such as:
- <header>: Stores the starting information of the web page.
- <footer>: Represents the last part of the page.
- <nav> : Navigation menu for HTML pages.
- <article>: is a set of information.
- <section> : Used inside the article block to define the basic structure of the page.
- <aside>: The sidebar content of the page.
- How can I optimize my website’s asset loading?
In order to optimize the loading time of a website, we need to optimize its asset loading, and to do this:
- CDN Hosting– A CDN or content delivery network is a geographically distributed server to help reduce latency.
- File compression– This is a method that helps to reduce the size of the assets to reduce data transfer
- File concatenation – This reduces the number of HTTP calls
- Minify Scripts – This reduces the overall file size of js and CSS files
- Parallel Downloads – Hosting assets in multiple subdomains helps to bypass the download limit of 6 assets per domain for all modern browsers. This can be configured, but most regular users never modify these settings.
- Lazy Loading – Instead of loading all assets at once, non-critical assets can be loaded as needed.
What are the various formatting tags in HTML?
HTML has a variety of formatting tags:
- <b>—Make the text bold
- <i> – Italicizes text
- <em> – Makes text italic, but adds semantic importance
- <big>—Increases the font size of the text by one unit
- <small>—Reduces the font size of the text by one unit
- <sub>—Makes the text subscript
- <sup> – Makes the text superscripted
- <del> – Appears as deleted text
- <strong> – Marks text as important
- <mark>—Highlights the text
- <ins> – Displays as added text
What are the different types of document types available?
There are three Doctypes available:
- Strict document types
- Transition document types
- Frameset document type
Please explain how to indicate the character set used in the document in HTML?
The character set is defined in the <meta> tag inside the <head> element.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
...
...
</head>
...
</html>
HTML Collection of Common Interview Questions and Answers: <strong>, <b> tags and <em>, <i> tags?
<strong>, <b> and <em>, <i> tags work the same way on a normal web page. <b> and <i> labels represent bold and italics. These two labels only apply the font style and the bold label <b> and just add more ink to the text, and these labels don’t say anything about the text.
Whereas, the <strong> and <em> tags, respectively, indicate that the span of the text is of strong importance or more important and emphasized than the rest of the text. These tags have a semantic meaning.
What is the significance of the < head> and <body > tags in HTML?
<head> tag provides information about the document. It should always be included in the <html> tag. This tag contains the metadata of the page, and tags such as <link>, <meta>, <style>, <script> in the header tag will not be displayed on the page. Also, you can only have 1 <head> tag in the entire HTML document, and always before the <body> tag.
<body> tag defines the body of an HTML document. It should always be included in the <html> tag. All content that needs to be displayed on a web page, such as images, text, audio, video, content, using elements such as < p>, <img>, <audio>, <heading>, <video>, <div>, etc., will always be included in the <body> tag. Also, you can only have 1 body element in an HTML document, and it is always after the <head> tag.
Can we display a web page within a web page or can we nest web pages?
Yes, we can display a web page in another HTML web page. HTML provides a tag <iframe> that we can use to do this.
<iframe src=”url of the web page to embed” />
How is Cell Padding different from Cell Spacing?
Cell spacing is the space or gap between two consecutive cells. Whereas, cell filling is the space or gap between the text/content of the cell and the edge/border of the cell. Please refer to the example above to find out the difference.
How do we merge two or more rows or columns into one row or column in an HTML table?
HTML provides two table properties, rowspan and colspan, so that a cell spans multiple rows and columns, respectively.
Is it possible to change inline elements to block-level elements?
Yes, you can change an inline element to a block-level element using the display property with a value of “block”.
How many ways can we position an HTML element? Or what is the allowable value for the location property?
There are 7 main positional attribute values that can be used to position HTML elements:
- static: the default value. Here the elements are positioned according to the normal flow of the document.
- absolute: Here the element is positioned relative to its parent. The final position is determined by the values left, right, top, and bottom.
- fixed: This is similar to Absolute, except that the element here is positioned relative to the <html> element.
- relative: Here the element is positioned according to the normal flow of the document and relative to its original/normal position.
- initial: This resets the property to its default value.
- inherit: Here the element inherits or takes the property of its parent.
How many ways are HTML elements displayed?
- inline: With this we can display any block-level element as an inline element. The height and width attribute values of the element are not affected.
- block: Using it, we can display any inline element as a block-level element.
- inline-block: This property is similar to inline, except that by using the display as inline-block, we can actually format the element with height and width values.
- flex: It displays containers and elements as a flexible structure. It respects the flexbox property.
- inline-flex: It displays the flex container as an inline element, while its contents respect the flexbox property.
- grid: It displays the HTML element as a grid container.
- none: Using this attribute we can hide HTML elements.
Here are some of the rarely used display types:
- table
- inline-table
- table-cell
- table-column
- table-row
- inline-grid
- list-item
- inherit
- initial
- table-caption
What is the difference between “display: none” and “visibility: hidden” when used as attributes for HTML elements.
When we use the attribute “visibility: hidden” for an HTML element, the element is hidden from the web page, but it still takes up space. However, if we use the “display: none” attribute for an HTML element, then the element will be hidden and it won’t take up any space on the web page.
How do I specify a link and interpret the target attribute in HTML?
HTML provides a hyperlink – <a> tag to specify the link in a web page. The ‘href’ attribute is used to specify the link, and the ‘target’ attribute is used to specify where we want to open the linked document. The Target property can have the following values:
- _self: This is the default. It opens the document in the same window or tab when clicked.
- _blank: It opens the document in a new window or tab.
- _parent: It opens the document in the parent frame.
- _top: It opens the document in a full-body window.
How many ways can we specify CSS styles for HTML elements?
There are three ways we can style HTML elements:
- Inline: Here we use the Style attribute inside the HTML element.
- Internal: Here we use the <style> tag inside the <head> tag. To apply the style, we bind elements using the “id” or “class” attributes.
- External: Here we use the <link> tag inside the <head> tag to reference the CSS file into our HTML code. Similarly, the binding between an element and a style is done using the “id” or “class” attributes.
What is the difference between link tags< link> and anchor tags<a>?
Anchor tags <a> are used to create hyperlinks to another web page or a section of a web page that are clickable, while link tags <link> define links between documents and external resources, which are not clickable.
How do I include javascript code in HTML?
HTML provides a <script> tag that we can use to run javascript code and make our HTML pages more dynamic.
<!DOCTYPE html>
<html>
<body>
<h1>
<span>This is a demo for </span>
<u><span id="demo"></span></u>
</h1>
<script>
document.getElementById("demo").innerHTML = "script Tag"
</script>
</body>
</html>
When to use a script in the header and when in the body?
If the script contains some event-triggered functions or jquery libraries, then we should use them in the head section. If the script writes content to the page or is not within the function, it should be placed inside the body section at the bottom. In short, follow these three points:
- Put the library script or event script in the head section.
- Put normal scripts that don’t write anything on the page in the head section until there are any performance issues.
- Place a script that renders something on a web page at the bottom of the body section.
What is a form and how to create a form in HTML?
HTML forms are used to collect user input. HTML provides a <form> tag to create forms. To get input from the user, we use the <input> tag in the form so that all collected user data can be sent to the server for processing. There are different input types like “button”, “checkbox”, “number”, “text”, “password”, “submit”, and so on.
<form action="/submit_data.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<label>Enter Mobile number </label>
<input type="number" name="mobile_no"/>
<input type="submit" value="Submit">
</form>
How do I handle events in HTML?
HTML allows events to be triggered in the browser using javascript or JQuery. There are a lot of events like “onclick”, “ondrag”, “onchange”, etc.
<!DOCTYPE html>
<html>
<body style="padding-top:50px">
<h3 id="event_demo">0</h3>
<input type="button" onclick="myFunction()" value="Click Me" />
<input type="reset" onclick="reset()" value="Reset" />
</body>
<script>
function myFunction() {
var value = document.getElementById("event_demo").innerHTML
value = parseInt(value) + 1;
document.getElementById("event_demo").innerHTML = value;
}
function reset() {
document.getElementById("event_demo").innerHTML = 0;
}
</script>
</html>
HTML5 Interview Questions
What are the advantages of HTML5 compared to previous versions?
Some of the advantages of HTML5 are:-
- It has multimedia support.
- It has the ability to store offline data using SQL Database and Application Cache.
- Javascript can run in the background.
- HTML5 also allows users to draw various shapes like rectangles, circles, triangles, and more.
- Includes new semantic labels and form control labels.
What are HTML common interview questions: How do I include audio or video in a web page?
HTML5 provides two tags: <audio> and <video> tags, which we can use to add audio or video directly to a web page.
Inline and block elements in HTML5?
Inline elements | Block elements |
---|---|
Inline elements only take up space that is absolutely necessary for the content, rather than starting with a new line. Examples:- < span>, <a>, <strong>, <img>, <button>, <em>, <select>, <abbr>, <label>, <sub>, <cite>, <abbr>, < script>, <label>, <i>, <input>, <output>, <q>, etc. | The block element starts on a new line and occupies the entire width of the available page. Examples:- <div>, <p>, <header>, <footer>, <h1>… <h6>、<form>、<table>、<canvas>、<video>、<blockquote>、< pre>、<ul>、<ol>、<figcaption>、<figure>、<hr>、 < article>, <section> etc. |
What is the difference between the < figure > tag and the <img > tag?
< figure> tags specify self-contained content, such as diagrams, images, code snippets, and so on. <figure> tags are used to semantically organize the content of an image, such as images, image titles, etc., while <img> tags are used to embed pictures in HTML5 documents.
How to specify metadata in HTML5?
To specify we can use the <meta> tag, which is an empty tag, i.e. it doesn’t end the tag. Some of the properties that are used with meta tags are name, content, http-equiv, etc. The following diagram illustrates how metadata is specified.
Is the <datalist> tag the same as the <select> tag?
HTML Interview Question Analysis: No. < datalist> tag and <select> tag are different. In the case of the <select> tag, the user has to choose from a list of options, while the <datalist> when used with the <input> tag provides a suggestion that the user chooses one of the given options or can enter some different values entirely.
Define an image map?
Image Map allows developers to map/link different parts of an image with different web pages. It can be achieved through the <map> tag in HTML5, with which we can link images with clickable areas.
<img src=”image_url” , usemap=”#workspace” />
<map name=”workspace”>
<area shape=”rect” coords=”34, 44, 270, 350” , href=”xyz.html” />
<area shape=”rect” coords=”10, 120, 250, 360” , href=”xyz.html” />
</map>
What are semantic elements?
Semantic elements are those that describe a specific meaning to browsers and developers. < elements such as form>, <table>, <article>, <figure> and so on are semantic elements.
Convert the following data into HTML5 tabular format?
S.no., language, mainly used for:
1. HTML, front-end
2. CSS, front-end
3. Python, backend
What is the difference between the <meter> tag and the <progress> tag?
When we want to show the progress of a task, we should use the <progress> tag, whereas if we only want to make scalar measurements within a known range or fractional value. In addition, we can specify several additional properties for the <meter> tag, such as “form”, “low”, “high”, “min”, etc.
Is it possible to use HTML5 for drag-and-drop operations? How does it work?
Yes, in HTML5 we can drag and drop elements. This can be done by using drag-and-drop-related events that are used with the element we want to drag and drop.
HTML Collection of Common Interview Questions and Answers: What is the difference between SVG and Canvas HTML5 elements?
SVG | Canvas |
---|---|
SVGs are vector-based, i.e., made up of shapes. | It is raster-based, i.e., made up of pixels. |
SVG works better on larger surfaces. | Canvas works better on smaller surfaces. |
SVG can be modified using CSS and scripts. | You can only modify the canvas using scripts. |
SVG is highly scalable. As a result, we can print with high quality in high resolution. | It is less scalable. |
What types of audio files can be played in HTML5?
HTML5 supports the following three audio file formats:
- Mp3
- WAV
- Ogg
What are the important goals of the HTML5 specification?
These are the target areas of the HTML5 specification:
- Introduce new element tags to better structure web pages, such as <header> tags.
- Forming standards for cross-browser behavior and supporting different devices and platforms
- Backwards compatible with older versions of HTML web pages
- Introduce basic interactive elements without relying on plugins, such as <video> tags, instead of flash plugins.
Explain the concept of network storage in HTML5.
This web storage helps to store some static data in the browser’s local storage so that we don’t need to get it from the server every time we need it. There is a size limit depending on the browser. This helps to reduce load times and a smooth user experience. There are two types of web storage that are used to store data locally in HTML5:
- Local Storage– This helps to store data that will be retained even if the user reopens the browser. It is stored in every web application on different browsers.
- Session Store – This is only for one session. This will be removed once the user closes the browser.
What is microdata in HTML5?
It is used to help website crawlers and search engines extract data. It’s basically a set of name-value pairs. These groups are called items, and each name-value pair is an attribute. Most search engines, such as Google, Microsoft, Yandex, etc., follow the schema.org vocabulary to extract this microdata.
<div itemscope itemtype="http://schema.org/SoftwareApplication">
<span itemprop="name">Interviewbit Games</span> -
REQUIRES <span itemprop="operatingSystem">ANDROID</span><br>
<link itemprop="applicationCategory" href="http://schema.org/GameApplication"/>
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
RATING:
<span itemprop="ratingValue">4.6</span> (
<span itemprop="ratingCount">8864</span> ratings )
</div>
<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
Price: Rs.<span itemprop="price">1.00</span>
<meta itemprop="priceCurrency" content="INR" />
</div>
</div>
- itemid – A unique global identifier for the item.
- itemprop – Used to add a property to the item.
- itemref – Provides a list of element IDs with additional attributes.
- ItemScope – This defines the scope of the itemType associated with it.
- itemtype – Specifies the URL of the vocabulary that will be used to define the itemprop.
The above example will be parsed by Google as:
Which label is used to represent the results of the calculations? Explain its properties.
<output> tag is used to represent the result of the calculation. It has the following properties:
- for – It defines the relationship between the elements used in the calculation and the results.
- form – Used to define the form to which the output element belongs.
- name – The name of the output element.
<form oninput = "result.value=parseInt(n1.value)+parseInt(n2.value)">
<input type = "number" name = "n1" value = "1" /> +
<input type = "number" name = "n2" value = "2" /><br />
The output is: <output name = "result"></output>
</form>
The example above looks like this:
What’s new in the relationship between <header> and <h1> tags in HTML5?
Since HTML5 is about better semantics and arrangement of tags and elements, < header> tag specifies the heading portion of a web page. Unlike the previous version, where there was only one <h1> element for the entire web page, this is now a section heading, such as <article> or <section>. According to the HTML5 specification, each <header> element must have at least one <h1> tag.
Interpreting HTML5 Graphics.
HTML5 supports two types of graphics:
- Canvas– It’s like drawing on a white paper or a blank web page. We can add different graphic designs to a web page using the available methods of drawing various geometric shapes.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas width="300" height="100" style="border:2px solid;"></canvas>
</body>
</html>
- SVG – Scalable vector graphics are mainly used for charts or icons. It follows the XML format.
<!DOCTYPE html>
<html>
<body>
<svg width="400" height="110">
<rect width="300" height="100" style="fill:#FFF;stroke-width:2;stroke:#000" />
</svg>
</body>
</html>
Both of the above examples produce this output and represent two different ways that HTML5 provides to implement the graphical aspects of a web page.
Explain the new input types that HTML5 provides for forms?
Here are the important new data types that HTML5 provides:
- Date – Use only type = “date” to select a date
- Week – Select a week using type = “week”.
- Month – Select the month only with type = “month”.
- Time – Select a time using only type = “time”.
- DateTime – Use type = “datetime” to combine date and time
- Datetime-local—Combine date and time with type = “datetime-local”. But ignore the time zone
- Color – Accept multiple colors using type = “color”.
- Email – Accept one or more email addresses using type = “email”.
- Number—Use type = “number” to accept numeric values with additional checks, such as min and max
- Search – Allows queries to be searched by entering text with type = “search”.
- Tel – Use type = “tel” to allow different phone numbers
- Placeholder – Displays a short prompt in the input field before entering a value with type = “placeholder”.
- Range – Use type = “range” to accept numeric values within a specific range
- URL – Accept URLs with type = “url”.
<form>
<div>
<label>Date:</label>
<input type="date" id="date" />
<br>
<label>Week:</label>
<input type="week" id="week" />
<br>
<label>Month:</label>
<input type="month" id="month" />
<br>
<label>Time:</label>
<input type="time" id="time" />
<br>
<label>Datetime:</label>
<input type="datetime" id="datetime" />
<br>
<label>Datetime Local:</label>
<input type="datetime-local" id="datetime-local" />
<br>
<label>Color:</label>
<input type="color" id="color"/>
<br>
<label>Email:</label>
<input type="email" id="email" placeholder="email address" />
<br>
<label>Number:</label>
<input type="number" id="number" />
<br>
<label>Search:</label>
<input type="search" id="search" />
<br>
<label>Phone:</label>
<input type="tel" id="phone" placeholder="Phone Number" pattern="\d{10}$" />
<br>
<label>Range:</label>
<input type="range" id="range" />
<br>
<label>URL:</label>
<input type="url" id="url"/>
</div>
</form>
What are the new tags in HTML5 media elements?
- <audio> – For sounds, audio streams, or music, embedding audio content without any additional plug-ins.
- < video> – for video streaming, embedding video content, and more.
- <source> – Used for multiple media resources in a media element, such as audio, video, and so on.
- <embed> – For external applications or embedded content.
- <track> – Used for subtitles in media elements such as video or audio.
<label>
Video:
</label>
<video width="320" height="240" controls>
<source src="video.mp4" type="video/mp4">
<track src="subtitles.vtt" kind="subtitles" srclang="en" label="English">
</video>
<br>
<label>
Embed:
</label>
<embed type="video/webm" src="https://www.youtube.com/embed/MpoE6s2psCw" width="400" height="300">
<br>
<label>
Audio:
</label>
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
Why do you think it’s important to add drag-and-drop functionality in HTML5? How would you make an image draggable in HTML5?
The drag-and-drop feature is a very intuitive way to select local files. This is similar to how most operating systems have a copy feature, so it’s easy for users to understand. Prior to the native drag-and-drop API, this could be achieved by writing complex Javascript programming or external frameworks such as jQuery.
To enable this feature, there is a draggable property in the <img> tab, and the ondrop and ondragover properties need to be set to the event handlers available in the script.
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
...
}
</script>
</head>
<body>
...
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" style="border: 1px solid #aaaaaa; width:350px; height: 70px;"></div>
<br>
<img id="drag1" src="img_logo.gif" alt="HTMLWhat are the common interview questions" draggable="true" width="336" height="69">
...
</body>
</html>
What are HTML common interview questions: Why do we need MathML elements in HTML5?
MathML stands for Mathematical Markup Language. It is used to display mathematical expressions on web pages. To do this, the <math> tag is used.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<math>
<mrow>
<mrow>
<msup>
<mi> a </mi>
<mn> 2 </mn>
</msup>
<mo> + </mo>
<msup>
<mi> b </mi>
<mn> 2 </mn>
</msup>
<mo> + </mo>
<mn> 2 </mn>
<mn> a </mn>
<mn> b </mn>
</mrow>
<mo> = </mo>
<mn> 0 </mn>
</mrow>
</math>
</body>
</html>
This will show the equation a2 + b2 + 2ab = 0.
What are the server-sent events in HTML5?
HTML Interview Question Analysis: The event that is pushed from the web server to the browser is called the server send event. DOM elements can be continuously updated using these events. This has a major advantage over direct voting. In polling, there’s a lot of overhead because every time an HTTP connection is established and disconnected from it, whereas in the event sent by the server, there is a long-lived HTTP connection. To use the events sent by the server, use the <eventsource> element. The src property of this element specifies the URL to send the data stream with the event.
<eventsource src = "/cgi-bin/myfile.cgi" />
What are Web Workers?
These were added to bring parallelism and asynchronous capabilities. It runs in the background to perform computationally intensive tasks without making the page responsive. It is achieved by starting a separate thread for such tasks. These are not meant to perform UI operations. There are three types of web workers:
- Dedicated Workers – These are workers who are used by a single script.
- Shared Workers – These are workers that are used by multiple scripts running in different windows, IFrames, etc.
- Service Workers – They act as proxy servers between web applications, browsers, and the network. Primarily used for push notifications and sync APIs.
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
var w;
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
What is the use of the novalidate attribute of the form tag introduced in HTML5?
Its value is a Boolean type that indicates whether the data submitted by the form will be pre-validated. By setting this to false, the form can be submitted without verification, which also helps the user recover later.
<form action = "" method = "get" novalidate>
Name:<br><input type="name" name="sname"><br>
Doubt:<br><input type="number" name="doubt"><br>
<input type="submit" value="Submit">
</form>
What are raster images and vector images?
Raster image – A raster image is defined by the arrangement of pixels in a grid, what color the pixels should be. Few raster file formats include PNG (.png), JPEG (.jpg), etc.
Vector Image– Vector images are defined using algorithms with shape and path definitions that can be used to render images written in similar markers on the screen fashionably. The file extension is .svg
How do I support SVG in my old browser?
In order to support older browsers instead of defining svg’s resources in the src attribute of the <img> tag, it should be defined in the srcset attribute and the fallback png file in src.
<img src="circle.png" alt="HTMLWhat are the common interview questions" alt="circle" srcset="circle.svg">
What are the different ways to make an image responsive?
- Art Direction– Using the <picture> element, you can zoom in on a landscape image that is fully displayed in a desktop layout and focus on the main theme for a portrait layout.
<picture>
<source media="(min-width: 650px)" srcset="img_cup.jpg">
<img src="img_marsh.jpg" alt="HTMLWhat are the common interview questions? Explanation of popular questions and answers" style="width:auto;">
</picture>
Larger screen (>650px)
For any other screen
- Resolution Switching– Instead of scaling and cropping, you can scale an image accordingly using vector graphics. In addition, this can be further optimized to serve screens with different pixel densities.
For example, SVG
<svg width="100" height="100">
<circle cx="50" cy="50" r="40"
stroke="green" stroke-width="4" fill="yellow" />
</svg>
HTML Collection of Common Interview Questions and Answers: What is a Checklist File in HTML5?
The manifest file is used to list the resources that can be cached. The browser uses this information to make the web page load faster than it did the first time. There are 3 sections in the manifest file
- CACHE Manifest – The file needs to be cached
- Network – Files that are never cached and always require a network connection.
- Fallback – Roll back the file if the page is inaccessible
CACHE MANIFEST
# 2012-06-16 v1.0.0
/style.css
/logo.gif
/main.js
NETWORK:
login.php
FALLBACK:
/html/ /offline.html
<!DOCTYPE HTML>
<html manifest="tutorial.appcache">
...
...
</html>
What is the Geolocation API in HTML5?
The Geolocation API is used to share the physical location of the client with a website. This helps to provide users with locale-based content and unique experiences based on the user’s location. This applies to the new properties of the Global Navigator object, and is supported by most modern browsers.
var geolocation = navigator.geolocation;
Write HTML5 code to demonstrate the use of the Geolocation API.
<!DOCTYPE html>
<html>
<body>
<p>Click "try it" button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation functionality is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
The example above requires the user to allow access to location data via the Geolocation API, and the coordinates of the client’s physical location are displayed when the button is clicked.
HTML What are the Common Interview Questions: Explain Web Components and How to Use Them.
These are used to create reusable custom elements, which is very difficult in traditional HTML. It consists of three technologies:
- Custom Elements – These are JavaScript APIs that help define custom elements and their behavior.
- Shadow DOM – These are JavaScript APIs that attach an encapsulated shadow DOM tree to an element in order to keep the element’s features private and unaffected by other parts.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>composed and composedPath demo</title>
<script src="main.js" defer></script>
</head>
<body>
<h1><code>composed</code> and <code>composedPath</code> demo</h1>
<open-shadow text="I have an open shadow root"></open-shadow>
<closed-shadow text="I have a closed shadow root"></closed-shadow>
</body>
</html>
customElements.define('open-shadow',
class extends HTMLElement {
constructor() {
super();
const pElem = document.createElement('p');
pElem.textContent = this.getAttribute('text');
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(pElem);
}
}
);
customElements.define('closed-shadow',
class extends HTMLElement {
constructor() {
super();
const pElem = document.createElement('p');
pElem.textContent = this.getAttribute('text');
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.appendChild(pElem);
}
}
);
document.querySelector('html').addEventListener('click', e => {
console.log(e.composed);
console.log(e.composedPath());
});
Here are 2 custom elements, <open-shadow> and <closed-shadow> that take their textual content and insert them into the shadow DOM as the contents of the <p> element.
- HTML Templates– Markup templates are written using <template> and <slot> elements that can be reused multiple times as the basis for a custom element structure.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple template</title>
<script src="main.js"></script>
</head>
<body>
<h1>Simple template</h1>
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p><slot name="my-text">My default text</slot></p>
</template>
<my-paragraph>
<span slot="my-text">Let's have some different text!</span>
</my-paragraph>
<my-paragraph>
<ul slot="my-text">
<li>Let's have some different text!</li>
<li>In a list!</li>
</ul>
</my-paragraph>
</body>
</html>
customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-paragraph');
const templateContent = template.content;
this.attachShadow({mode: 'open'}).appendChild(
templateContent.cloneNode(true)
);
}
}
);
const slottedSpan = document.querySelector('my-paragraph span');
console.log(slottedSpan.assignedSlot);
console.log(slottedSpan.slot);
Here we reused the <my-paragraph> template.