HTML, CSS, JavaScript Interview Questions with Answers

100 HTML/CSS/JavaScript Interview Questions with Answers

This collection of 100 basic HTML, CSS, and JavaScript interview questions with answers provides essential knowledge for anyone preparing for front-end web development interviews.

It covers fundamental concepts such as the structure and purpose of HTML elements, styling with CSS, layout techniques, responsive design, and common JavaScript programming tasks and features.

This set is designed to help candidates build confidence and demonstrate their understanding of core web technologies in interviews.

1. What is HTML?

HTML is a language used to create and design web pages on the Internet. It tells the browser how to show text, images, links, and other content on a webpage.

2. What does DOCTYPE mean in HTML?

DOCTYPE in HTML is a special declaration at the very top of a webpage that tells the browser which version of HTML is used and how to correctly display the page.

3. Explain the purpose of the <meta> tag.

The <meta> tag provides important information about the webpage, like the character set used or keywords, and helps with how browsers and search engines understand the page.

4. What is the difference between HTML and XHTML?

HTML is the basic language for web pages, while XHTML is a stricter version that follows more rules from XML. XHTML requires all tags to be properly closed and lowercase, making it more strict than HTML.

5. What is semantic HTML?

Semantic HTML uses meaningful tags that describe the content, like <header>, <article>, or <footer>, which makes the webpage easier to read for both browsers and developers.

6. Describe the difference between <div> and <span>.

<div> is a block-level container used to group larger sections of content, while <span> is an inline container used to style small parts of text within a line.

7. Explain the use of the <canvas> element.

The <canvas> element is used to draw graphics like shapes or animations directly in the webpage via scripting, often with JavaScript.

8. What are data attributes in HTML5?

Data attributes in HTML5 are custom attributes that allow you to store extra information inside HTML elements, using names that start with “data-“, which can then be accessed by scripts.

9. What is the purpose of the alt attribute in the <img> tag?

The alt attribute in the <img> tag provides alternative text that describes the image if it cannot load, and it helps screen readers for visually impaired users.

10. How do you create a hyperlink in HTML?

A hyperlink in HTML is created using the <a> tag with an href attribute pointing to the URL, like:
<a href=”https://howsnip.com”>Link Text</a>.

11. What is the purpose of the <head> tag in HTML?

The <head> tag in HTML holds important information about the webpage that browsers and search engines use, like the page title, character set, styles, and scripts. This information is not shown directly on the page but helps set up the page correctly.

12. Explain the difference between <ol> and <ul> elements.

<ol> is an ordered list that shows items with numbers, while <ul> is an unordered list that shows items with bullet points. Both group list items but have different visual styles.

13. What is the significance of the lang attribute in HTML?

The lang attribute in HTML declares the language of the webpage content (like “en” for English). It helps browsers and search engines understand and properly present the content for users.

14. What is the purpose of the <form> element in HTML?

The <form> element is used to collect user inputs on a webpage, like text boxes, radio buttons, and buttons for submitting data to a server.

15. How does the target attribute work in HTML forms?

The target attribute in HTML forms specifies where to open the response after the form is submitted, such as in the same window, a new tab, or a specific frame.

16. What is CSS and what does it stand for?

CSS stands for Cascading Style Sheets. It is used to style and layout HTML elements, controlling colors, fonts, spacing, and overall look of a webpage.

17. Explain the difference between inline, block, and inline-block elements.

Inline elements only take up as much width as their content, block elements take up the full width of the container, and inline-block elements behave like inline elements but allow setting width and height.

18. Describe the box model in CSS.

The box model in CSS describes how every element is made up of content, padding (space inside the element), border (the outline), and margin (space outside the border).

19. What is the purpose of the clear property in CSS?

The clear property in CSS is used to control the behavior of elements that follow floated elements, ensuring they don’t wrap around the float and start on a new line instead.

20. Explain the difference between position: relative; and position: absolute;.

position: relative; moves an element relative to its normal position without affecting other elements, while position: absolute; positions an element relative to its nearest positioned ancestor or the page, taking it out of the normal document flow.

21. What is the CSS selector specificity and how is it calculated?

CSS selector specificity is a rule used to determine which CSS style applies when multiple rules target the same element. It is calculated based on the types of selectors used:

  • ID selectors count the most,
  • class, attribute, and pseudo-class selectors count next,
  • element and pseudo-element selectors count the least.

Specificity is counted as a three-part number (ID-Class-Type). The rule with higher specificity wins. For example, an ID selector outweighs many classes or element selectors.

22. How can you center an element horizontally and vertically using CSS?

To center an element horizontally and vertically using CSS, you can use flexbox. For example:

parent {
  display: flex;
  justify-content: center;                          /* centers horizontally */
  align-items: center;                              /* centers vertically */
}

Or, use absolute positioning with transform:

child {
  position: absolute;
  top: 50%;
  left: 50%;
   transform: translate(-50%, -50%);
}

23. Explain the purpose of the float property in CSS.

The float property in CSS makes an element float to the left or right of its container, allowing other content to wrap around it. It was commonly used to create layouts before flexbox and grid became popular.

24. Describe the difference between padding and margin.

Padding is the space inside the element between its content and border, while margin is the space outside the element that separates it from other elements.

25. How does the display: none; property differ from visibility:hidden;?

`display: none;` hides the element completely and removes it from the page layout, so it takes no space. `visibility: hidden;` hides the element but it still occupies space on the page.

26. What is a CSS preprocessor, and why might you use one?

A CSS preprocessor is a tool (like Sass or LESS) that adds extra features (variables, functions, nesting) to CSS which make writing styles easier and more organized. The preprocessor code is then compiled to regular CSS.

27. What is the “box-sizing” property in CSS?

The box-sizing property controls how the width and height of an element are calculated. With `box-sizing: border-box;`, the width includes content, padding, and border. With `content-box` (the default), width applies only to content, excluding padding and border.

28. How do you include external stylesheets in HTML?

External stylesheets are included in HTML using the <link> tag inside the <head>, like this:

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

29. What is the difference between em and rem units in CSS?

`em` units are relative to the font size of the parent element, while `rem` units are relative to the root (html) element’s font size. `rem` is consistent throughout the page, `em` can vary based on nesting.

30. How does the z-index property work in CSS?

The z-index property controls stacking order of overlapping elements. Higher z-index values appear in front. It only works on positioned elements (`position` set to relative, absolute, or fixed).

31. What is JavaScript?

JavaScript is a programming language used to make web pages interactive. It can update content, handle user actions, play media, and do many tasks to make websites dynamic.

32. Explain the difference between let, const, and var in JavaScript.

let and const are modern ways to declare variables in JavaScript. let allows the value to change, const means the value cannot change after it’s set. var is an older way and has different behavior with scope and hoisting.

33. Describe hoisting in JavaScript.

Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their code before execution, so you can use variables or functions before you declare them (though only their declarations, not initial values).

34. What is the purpose of the this keyword in JavaScript?

The this keyword refers to the object that is currently calling the function or context in which the code is running. Its value changes depending on how a function is called.

35. What are closures in JavaScript?

Closures are when a function “remembers” the variables from its outer environment even after the outer function has finished running. It helps keep data private and allows powerful function patterns.

36. Explain the concept of prototypal inheritance in JavaScript.

Prototypal inheritance means objects can inherit properties and methods from other objects via a prototype chain. Instead of classes, JavaScript uses prototypes as templates for inheritance.

37. How does event delegation work in JavaScript?

Event delegation is a technique where a single event listener is added to a parent element to handle events for its child elements. It is efficient because it uses fewer listeners and works for dynamic content.

38. Describe the difference between == and === in JavaScript.

== checks if values are equal after converting types if needed (loose equality), while === checks if values and types are exactly equal (strict equality).

39. What is the purpose of the async keyword in JavaScript?

The async keyword is used to declare functions that work asynchronously, allowing you to use await inside them to wait for promises and write cleaner asynchronous code.

40. How do you handle errors in JavaScript?

Errors in JavaScript are handled using try…catch blocks where you put code that might throw errors in try, and catch lets you respond to those errors gracefully.

41. Explain the concept of callback functions.

A callback function in JavaScript is a function passed as an argument to another function, which is then called (or “called back”) inside the outer function after some work is done. It helps control the sequence of actions, especially for asynchronous tasks.

42. What is the difference between null and undefined in JavaScript?

null means a variable is explicitly set to have no value, while undefined means a variable has been declared but not assigned any value yet.

43. Describe the role of the bind method in JavaScript.

The bind method is used to create a new function with a specific this value and optional initial arguments. It helps control what this refers to when the function runs.

44. What is the purpose of the map function in JavaScript?

The map function takes an array and applies a given function to each item, returning a new array with the results without changing the original array.

45. Explain the concept of promises in JavaScript.

Promises represent the eventual result of an asynchronous operation. They help handle success or failure of tasks like fetching data, allowing easier management of asynchronous code.

46. What is the event loop in JavaScript?

The event loop is a process that manages how JavaScript handles multiple tasks, especially asynchronous ones. It listens for events and runs callback functions when tasks complete.

47. Describe the difference between null, undefined, and undeclared in JavaScript.

null means no value, undefined means declared but no value assigned, and undeclared means the variable was never declared in code.

48. How do you create an object in JavaScript?

You can create an object in JavaScript using curly braces:

const person = { name: "John", age: 30 };

49. Explain the purpose of the localStorage and sessionStorage objects.

localStorage and sessionStorage let you store data in the browser. localStorage keeps data even after closing the browser, while sessionStorage clears data when the browser tab is closed.

50. How does the typeof operator work in JavaScript?

The typeof operator returns the data type of a variable or value, like “string”, “number”, “object”, etc.

51. How do you link a JavaScript file to an HTML file?

To link a JavaScript file to an HTML file, use the <script> tag with the src attribute, like:

<script src="script.js"></script>

52. What is the purpose of the defer attribute in a script tag?

The defer attribute in a script tag tells the browser to download the script during HTML parsing but execute it only after the entire page has finished loading. This helps the page load faster without blocking HTML parsing.

53. Explain how to include an external CSS file in an HTML document.

To include an external CSS file in HTML, use the <link> tag inside the <head> section, like:

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

54. What is the importance of the viewport meta tag in responsive design?

The viewport meta tag controls how a webpage is displayed on different devices, especially mobile. It makes the page responsive by setting the width and scale so content fits well on small screens.

55. Describe the purpose of the @media rule in CSS.

The @media rule in CSS is used to apply different styles depending on the device’s screen size, orientation, or other features, helping create responsive designs.

56. How do you include external JavaScript libraries in your project?

External JavaScript libraries are included using the <script> tag with the src attribute pointing to the library URL or file, like:

<script src="https://cdn.example.com/library.js"></script>

57. Explain the purpose of the <!DOCTYPE html> declaration in HTML5.

The <!DOCTYPE html> declaration tells browsers the document is HTML5, enabling proper rendering and using modern web standards.

58. How can you optimize website performance using CSS and JavaScript?

Website performance can be optimized by minimizing and compressing CSS and JavaScript files, loading scripts asynchronously or deferred, reducing the number of files, and using caching.

59. What is the purpose of the lang attribute in the <script> tag?

The lang attribute in the <script> tag specifies the scripting language used (usually “JavaScript”), though it’s mostly optional as JavaScript is the default.

60. How do you handle browser compatibility issues in CSS and JavaScript?

Browser compatibility issues are handled by using feature detection, fallbacks, vendor prefixes in CSS, polyfills for unsupported features, and testing code across different browsers.

61. What is responsive design?

Responsive design is a way to create websites that automatically adjust and look good on all screen sizes and devices, like phones, tablets, laptops, and desktops.

62. Explain the difference between adaptive and responsive design.

Adaptive design uses fixed layouts for different screen sizes and loads a specific layout for each, while responsive design uses one flexible layout that adjusts fluidly based on the screen size.

63. Describe the purpose of media queries in CSS.

Media queries in CSS allow you to apply different styles depending on the device’s features such as screen width, height, or orientation. This helps make websites responsive.

64. What is a CSS framework, and why might you use one?

A CSS framework is a pre-prepared collection of CSS code and styles (like Bootstrap) that helps you build websites faster by providing ready-made design components and grids.

65. How does a CSS grid system work in responsive design?

A CSS grid system divides the page into rows and columns, letting you place elements precisely for different screen sizes, making layouts responsive and organized.

66. Explain the concept of a mobile-first approach in web development.

The mobile-first approach means designing a website starting from the smallest screen size (mobile) and then adding styles for larger screens. This ensures good performance and usability on mobiles.

67. What is the importance of the viewport meta tag in responsive design?

The viewport meta tag in responsive design controls how the webpage scales and fits on different devices, making sure it looks good especially on mobile screens.

68. How can you make a website accessible to users with disabilities?

To make a website accessible, you use proper HTML tags, add alt text to images, ensure keyboard navigation, use clear contrast, and follow accessibility standards so people with disabilities can use it easily.

69. What is the purpose of the rem unit in responsive design?

The rem unit is relative to the root (html) font size, making it useful for consistent sizing across different elements and easier control in responsive design.

70. Explain the role of the max-width property in responsive design.

The max-width property limits the maximum size an element can grow to, helping maintain layout control and preventing elements from becoming too wide on large screens.

71. What is the DOM?

The DOM (Document Object Model) is a programming interface that represents the webpage as a tree of objects. It allows scripts like JavaScript to access, change, add, or delete elements, content, and styles on a webpage.

72. How do you select elements with JavaScript in the DOM?

You select elements in the DOM with JavaScript using methods like `getElementById()`, `getElementsByClassName()`, `getElementsByTagName()`, or modern methods like `querySelector()` and `querySelectorAll()`.

73. Explain the difference between innerHTML and textContent.

innerHTML gets or sets the HTML content inside an element as a string (including tags), while textContent gets or sets only the text inside the element without any HTML tags.

74. How does event delegation work in JavaScript?

Event delegation works by adding one event listener to a parent element that catches events from its children, instead of attaching listeners to many child elements individually. It is efficient for dynamic content.

75. What is the purpose of the addEventListener method?

The addEventListener method attaches an event handler to an element for a specific event (like clicks or key presses), allowing custom code to run when the event happens.

76. How do you prevent the default behavior of an event in JavaScript?

To prevent the default behavior of an event (like submitting a form or following a link), use `event.preventDefault()` inside the event handler function.

77. Describe the difference between the focus and blur events.

The focus event occurs when an element (such as an input) gains focus (click or tabbed into), and the blur event occurs when it loses focus.

78. Explain the purpose of the event.stopPropagation() method.

event.stopPropagation() stops the event from bubbling up (triggering parent elements’ event handlers) or capturing down the DOM tree, limiting where the event is heard.

79. How can you dynamically create elements in the DOM with JavaScript?

You can dynamically create new elements in the DOM using methods like `document.createElement()`, then add them to the document with `appendChild()` or similar methods.

80. What is the purpose of the data-* attributes in HTML5?

The data-* attributes in HTML5 let you store custom data inside HTML elements that can be easily accessed with JavaScript, useful for attaching extra info to elements.

81. What are the arrow functions in JavaScript?

Arrow functions are a shorter way to write functions in JavaScript using the => syntax. They are concise and inherit the surrounding this value, making them useful especially for simple functions and callbacks.

82. Describe the let and const keywords introduced in ES6.

let and const are new ways to declare variables introduced in ES6. let allows variables to be changed later, while const creates constant variables that cannot be reassigned after initialization.

83. What is destructuring assignment in JavaScript?

Destructuring assignment lets you extract values from arrays or objects into separate variables easily, using a syntax similar to the structure of the array or object.

84. Explain the purpose of the template literals in ES6.

Template literals are strings enclosed in backticks (`) that allow embedding variables and expressions using ${}, making string building easier and more readable.

85. What are the let and const keywords in ES6?

(Repeat) let and const are ES6 keywords for variable declaration. let is for variables that can change, const is for values that stay constant.

86. How do you use the import and export statements in ES6?

import and export let you organize JavaScript code into modules. export is used to share functions, objects, or values from a module, and import lets you bring them into another module.

87. What is the purpose of the spread operator (…) in JavaScript?

The spread operator (…) lets you expand elements of an array or object into individual elements, useful for copying, merging, or passing multiple arguments.

88. Describe the class syntax in ES6 and how it relates to object-oriented programming.

ES6 class syntax provides a cleaner, simpler way to create objects and handle inheritance using the class and extends keywords, similar to other object-oriented programming languages.

89. Explain the concept of promises and the async/await syntax in JavaScript.

Promises represent future values from asynchronous operations. async/await is syntax that lets you write asynchronous code that looks and behaves like synchronous code, making it easier to read and manage.

90. What are the rest parameters in JavaScript?

Rest parameters allow functions to accept any number of arguments as an array, using … followed by a parameter name.

91. How do you optimize the loading time of a web page?

To optimize web page loading time, minimize file sizes, reduce HTTP requests, use caching, compress images, load scripts asynchronously or deferred, and use CDNs.

92. Explain the concept of lazy loading in web development.

Lazy loading delays loading of non-critical resources like images or scripts until they are needed (e.g., when they enter the viewport), improving initial load speed and saving bandwidth.

93. What is the purpose of bundling and minification in web development?

Bundling combines multiple files into one to reduce HTTP requests, and minification removes unnecessary characters from code without changing its meaning, making files smaller and faster to load.

94. How can you reduce the number of HTTP requests on a web page?

You can reduce HTTP requests by bundling files, using CSS sprites for images, inlining small scripts and styles, and loading only essential resources on initial page load.

95. Describe the importance of using a content delivery network (CDN).

A CDN (Content Delivery Network) stores copies of your website’s content on servers worldwide, delivering content to users from the closest server, which speeds up load times and improves reliability.

96. What is tree shaking in the context of JavaScript and bundling?

Tree shaking is a build process that removes unused JavaScript code (dead code) from bundles, reducing file size and improving performance.

97. Explain the difference between synchronous and asynchronous loading of scripts.

Synchronous loading blocks the page rendering until the script loads and executes, while asynchronous loading lets the page continue rendering while loading scripts, improving speed.

98. How can you optimize images for a web page?

Optimize images by compressing them, choosing appropriate file formats, resizing to needed dimensions, and using modern formats like WebP for faster load times.

99. Describe the significance of using the rel=”preload” attribute.

The rel=”preload” attribute hints browsers to load important resources (like fonts or scripts) early, improving perceived page load speed.

100. What is the purpose of the “defer” attribute in a script tag, and how does it affect page loading?

The defer attribute in a script tag loads the script while the page parses but runs it only after the full HTML document is parsed, avoiding render-blocking and speeding up page load.