Welcome to the HTML Interview Questions and Answers! This repository is a collection of HTML questions categorized by difficulty level: Easy, Medium, and Hard. Whether you're a beginner looking to understand the basics or an expert aiming to polish your skills, this repository has something for everyone.
HTML (HyperText Markup Language) is the standard markup language for creating web pages and web applications. It is essential for anyone who wants to delve into web development. This repository is designed to help you practice and master HTML by solving a variety of questions ranging from easy to hard.
- Foundation of Web Development: Understanding HTML is crucial for building web pages and web applications.
- Easy to Learn: HTML has a simple syntax that is easy to understand and use.
- Widely Used: HTML is the backbone of the web, and mastering it opens doors to learning other web technologies.
These questions are designed for beginners. They cover basic HTML tags, attributes, and simple page structure.
These questions are for those who have a basic understanding of HTML and want to delve deeper. They cover forms, tables, and more complex page layouts.
These questions are for advanced users who want to test their knowledge and tackle challenging scenarios. They include advanced HTML5 features, multimedia, and semantic elements.
We welcome contributions from the community! If you have a question that you think should be included, please follow these steps:
- Fork the repository.
- Create a new branch for your question.
- Add your question in the appropriate category folder (
easy,medium,hard). - Submit a pull request with a detailed description of your changes.
Happy coding! If you find this repository helpful, please give it a star ⭐ and share it with others.
HTML stands for HyperText Markup Language. It's a standard language used for creating webpages and web applications.
The <head> tag contains meta-information about the HTML document, such as its title, character set, styles, and scripts. This information is not displayed on the webpage but is essential for proper functioning.
You create a hyperlink using the <a> tag with the href attribute specifying the URL of the link destination.
<a href="https://www.example.com">Visit Example</a>The <strong> tag indicates strong importance and also conveys semantic meaning, whereas the <b> tag simply applies bold styling.
<strong>This is important text.</strong>
<b>This is bold text.</b>Use the <img> tag with the src attribute for the image path and the alt attribute for alternative text.
<img src="image.jpg" alt="Description of the image">HTML attributes provide additional information about HTML elements. They are always included in the opening tag and usually come in name/value pairs like name="value".
<a href="https://www.example.com" target="_blank" title="Example site">Visit Example</a>You create lists using the <ul> (unordered list) or <ol> (ordered list) tags, with each list item enclosed in <li> tags.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>An ordered list (<ol>) numbers each list item, while an unordered list (<ul>) uses bullet points.
<ol>
<li>First item</li>
<li>Second item</li>
</ol>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>Use the <table> tag along with <tr> (table row), <th> (table header), and <td> (table data) tags.
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>The <a> tag creates hyperlinks, with the href attribute specifying the URL of the link destination.
<a href="https://www.example.com">Click here</a>Use the <!-- --> syntax for comments, which are not displayed by the browser.
<!-- This is a comment -->
<p>This is a paragraph.</p>The <title> tag defines the title of the HTML document, displayed in the browser's title bar or tab. It is placed within the <head> tag.
<head>
<title>My Webpage</title>
</head>The <div> tag is a block-level element used to group larger sections of content, while the <span> tag is an inline element used to group smaller pieces of content within a block.
<div>This is a block-level element.</div>
<span>This is an inline element.</span>Use the <form> tag along with form elements like <input>, <textarea>, <select>, and <button>.
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>The <br> tag inserts a line break, forcing the text to move to the next line. It is an empty tag, meaning it has no closing tag.
<p>This is the first line.<br>This is the second line.</p>A paragraph is defined using the <p> tag. It creates a block of text separated by a margin from adjacent content.
<p>This is a paragraph.</p>HTML tags are the syntax used to define elements, while HTML elements are the building blocks of HTML documents. Tags are written using angle brackets, whereas elements include the tags and the content within them.
<!-- Tag: <p> -->
<!-- Element: <p>This is a paragraph.</p> -->
<p>This is a paragraph.</p>The alt attribute provides alternative text for an image if it cannot be displayed. It also aids accessibility by describing the image to screen readers.
<img src="image.jpg" alt="Description of the image">Use the lang attribute in the <html> tag.
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>Block-level elements start on a new line and take up the full width available, while inline elements do not start on a new line and only take up as much width as necessary.
<div>This is a block-level element.</div>
<span>This is an inline element.</span>Use the <input> tag with the type attribute set to "checkbox".
<input type="checkbox" id="subscribe" name="subscribe">
<label for="subscribe">Subscribe to newsletter</label>Use the <video> tag with the src attribute specifying the video file's path, and optionally include the controls attribute to provide playback controls.
<video src="video.mp4" controls>
Your browser does not support the video tag.
</video>Semantic HTML elements clearly describe their meaning and content, improving accessibility and SEO by providing meaningful context to browsers and assistive technologies.
<header>Header content</header>
<nav>Navigation links</nav>
<main>Main content</main>
<article>Article content</article>
<aside>Aside content</aside>
<footer>Footer content</footer>Use the <select> tag with nested <option> tags for each option.
<label for="fruits">Choose a fruit:</label>
<select id="fruits" name="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>The charset attribute specifies the character encoding for the HTML document, ensuring that it is displayed correctly, especially for special characters and symbols.
<meta charset="UTF-8">HTML5 is the latest version of HTML, introducing new elements, attributes, and APIs for more powerful web applications. Notable features include:
- New semantic elements like
<header>,<footer>,<article>,<section>. - Multimedia elements like
<audio>and<video>. - Graphics support with
<canvas>and SVG. - Enhanced form controls and attributes.
- Offline storage with
localStorageandsessionStorage. - Geolocation API.
- Drag-and-drop support.
- Web workers for background processing.
Use the <iframe> tag with the src attribute set to the YouTube video URL.
<iframe width="560" height="315" src="https://www.youtube.com/embed/video_id" frameborder="0" allowfullscreen></iframe>The <canvas> element is used to draw graphics on the fly via JavaScript. It provides a resolution-dependent bitmap canvas for rendering shapes, images, and other graphics.
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.fillStyle = 'red';
context.fillRect(10, 10, 150, 75);
</script>The <picture> tag allows you to specify multiple source images for different screen sizes or resolutions.
<picture>
<source srcset="image-small.jpg" media="(max-width: 600px)">
<source srcset="image-medium.jpg" media="(max-width: 1200px)">
<img src="image-large.jpg" alt="Description of the image">
</picture>The <input type="button"> creates a button with simple text, whereas the <button> element can contain HTML content, including text and images.
<input type="button" value="Click me">
<button>Click <strong>me</strong></button>The <template> tag holds HTML content that is not rendered when the page loads, but can be instantiated later using JavaScript.
<template id="myTemplate">
<p>This is a template</p>
</template>
<script>
var template = document.getElementById('myTemplate');
var clone = template.content.cloneNode(true);
document.body.appendChild(clone);
</script>The data-* attributes allow you to store custom data on HTML elements without needing non-standard attributes. This data can be accessed via JavaScript.
<div data-user-id="12345" data-role="admin">User Info</div>
<script>
var div = document.querySelector('div');
console.log(div.dataset.userId); // "12345"
console.log(div.dataset.role); // "admin"
</script>Use the <nav> element to wrap the navigation links, typically represented using an unordered list (<ul>).
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>The href attribute specifies the URL of a linked resource, commonly used with <a>, <link>, and <base> tags. The src attribute specifies the URL of an embedded resource, commonly used with <img>, <script>, and <iframe> tags.
<a href="https://www.example.com">Link</a>
<img src="image.jpg" alt="Image">Use the <audio> tag with the src attribute for the audio file and the controls attribute to provide playback controls.
<audio src="audio.mp3" controls>
Your browser does not support the audio element.
</audio>The <main> element specifies the main content of the document. It should contain content unique to the document, excluding repeated content like headers, footers, and navigation.
<main>
<article>
<h1>Main Article</h1>
<p>Content of the main article.</p>
</article>
</main>Create a modal dialog using a combination of HTML, CSS, and JavaScript. Here's a simple example:
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Modal content</p>
</div>
</div>
<style>
.modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); }
.modal-content { background-color: #fff; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; }
.close { color: #aaa; float: right; font-size: 28px; font-weight: bold; }
.close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
</style>
<script>
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName('close')[0];
span.onclick = function() { modal.style.display = 'none'; }
window.onclick = function(event) { if (event.target == modal) { modal.style.display = 'none'; } }
</script>The <header> element represents introductory content or navigational links, typically found at the top of a section or page. The <footer> element represents footer content, typically found at the bottom, often containing metadata, copyright information, or links.
<header>
<h1>Welcome to My Website</h1>
<nav>Navigation links</nav>
</header>
<footer>
<p>© 2023 My Website</p>
</footer>Create a sticky footer by ensuring the footer stays at the bottom of the viewport even if the content is not tall enough.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body, html { height: 100%; margin: 0; }
.wrapper { display: flex; flex-direction: column; height: 100%; }
.content { flex: 1; }
footer { background: #333; color: white; padding: 10px 20px; }
</style>
</head>
<body>
<div class="wrapper">
<div class="content">
<p>Main content goes here...</p>
</div>
<footer>Sticky Footer</footer>
</div>
</body>
</html>The <aside> element represents content indirectly related to the main content, such as sidebars, advertisements, or related links. It is often used for additional information or secondary content.
<aside>
<h2>Related Articles</h2>
<ul>
<li><a href="#article1">Article 1</a></li>
<li><a href="#article2">Article 2</a></li>
</ul>
</aside>The required attribute is used in form elements to indicate that the field must be filled out before submitting the form.
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>The <datalist> element provides a list of predefined options for an <input> element, enabling the user to choose from the list or enter a custom value.
<label for="browsers">Choose a browser:</label>
<input list="browsers" id="browser" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>Use the <progress> element to create a progress bar. The value attribute specifies the progress, and the max attribute specifies the maximum value.
<progress value="70" max="100"></progress>The <mark> element highlights text, indicating relevance or importance. It visually emphasizes text with a yellow background.
<p>This is a <mark>highlighted</mark> text.</p>Use CSS Grid Layout to create a responsive grid. Define the grid container and set up columns and rows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Grid Layout</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
}
.item {
background-color: #ccc;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
</div>
</body>
</html>- Inline elements: Do not start on a new line and only take up as much width as necessary. Examples include
<span>,<a>, and<strong>. - Inline-block elements: Behave like inline elements but can have a width and height set. Examples include
<img>and<button>. - Block elements: Start on a new line and take up the full width available. Examples include
<div>,<p>, and<h1>.
You can create a tooltip using HTML and CSS by using the title attribute in HTML and custom CSS for styling:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 5px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%; /* Position the tooltip above the text */
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body>
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
</body>
</html><figure>: Used to represent self-contained content, often with an optional caption.<figcaption>: Used to provide a caption for the<figure>element.
Example:
<figure>
<img src="image.jpg" alt="Description of image">
<figcaption>This is the caption for the image.</figcaption>
</figure>You can create a collapsible section using the <details> and <summary> elements:
<details>
<summary>Click to expand/collapse</summary>
<p>This is the collapsible content.</p>
</details><section>: Represents a thematic grouping of content, typically with a heading.<article>: Represents a self-contained piece of content that can be independently distributed or reused.
Implementing accessibility features involves using semantic HTML elements, ARIA (Accessible Rich Internet Applications) roles and attributes, and ensuring keyboard navigability. Examples include using <nav> for navigation, <header> for page headers, and setting appropriate aria-label attributes for screen readers.
ARIA roles and attributes enhance the accessibility of web content by providing additional information to assistive technologies. Common roles include role="button", role="navigation", and attributes like aria-label for labeling elements.
SEO optimization involves using semantic HTML tags, appropriate meta tags (<title>, <meta>), alt attributes for images, and ensuring a proper heading structure (<h1>, <h2>, etc.).
You can use JavaScript to validate form inputs by adding event listeners to form elements and checking the input values against predefined criteria:
<form id="myForm">
<input type="text" id="name" required>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
var name = document.getElementById('name').value;
if (name === '') {
alert('Name is required');
event.preventDefault();
}
});
</script>The Shadow DOM allows encapsulation of DOM and CSS in Web Components, preventing styles and scripts from leaking in or out. This helps create reusable, isolated components.
You can create a custom HTML element using the Custom Elements API:
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `<p>Hello, world!</p>`;
}
}
customElements.define('my-element', MyElement);The <slot> element is used to define placeholders in a shadow DOM where content can be inserted from the light DOM (the main document).
The contenteditable attribute makes an element editable by the user:
<div contenteditable="true">This is an editable div.</div>You can create a drag-and-drop interface using the draggable attribute and JavaScript event handlers like ondragstart and ondrop:
<div id="drag1" draggable="true" ondragstart="drag(event)">Drag me</div>
<div id="dropzone" ondrop="drop(event)" ondragover="allowDrop(event)">Drop here</div>
<script>
function allowDrop(event) {
event.preventDefault();
}
function drag(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
</script>- localStorage: Stores data with no expiration time, accessible only within the same origin.
- sessionStorage: Stores data for the duration of the page session, accessible only within the same origin.
- Cookies: Stores data with an expiration time, accessible across different origins depending on the cookie settings.
The srcset attribute specifies multiple image sources for responsive images:
<img src="small.jpg" srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w" sizes="(max-width: 600px) 480px, 800px" alt="Responsive image">Web workers run scripts in background threads:
var worker = new Worker('worker.js');
worker.onmessage = function(event) {
console.log(event.data);
};
worker.postMessage('Hello, worker!');CORS is managed by the server using the Access-Control-Allow-Origin header. For example, in a server response:
Access-Control-Allow-Origin: *defer: Scripts are executed in order after the HTML is parsed.async: Scripts are executed as soon as they are downloaded, without waiting for other scripts or HTML parsing.
SPAs dynamically update the content without reloading the page, often using frameworks like React, Angular, or Vue.js. Basic example with vanilla JavaScript:
<div id="app"></div>
<script>
document.getElementById('app').innerHTML = '<h1>Home</h1>';
window.onhashchange = function() {
if (location.hash === '#about') {
document.getElementById('app').innerHTML = '<h1>About</h1>';
} else {
document.getElementById('app').innerHTML = '<h1>Home</h1>';
}
};
</script><details>: Creates a collapsible section.<summary>: Acts as a summary or heading for the<details>element.
Use the loading="lazy" attribute:
<img src="image.jpg" alt="Description" loading="lazy">The <meta> viewport tag controls the layout on mobile browsers:
<meta name="viewport" content="width=device-width, initial-scale=1">You can embed SVG directly in HTML:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>Service workers enable offline functionality:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}<link>: Defines a relationship between the current document and an external resource (e.g., CSS).<a>: Defines a hyperlink to another document or location.
Use CSS media queries to apply styles based on screen size:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}Use service workers and the Cache API to cache resources for offline use.
The <base> tag specifies the base URL for all relative URLs in a document:
<base href="https://www.example.com/">A manifest file defines the resources to be cached for offline use. Example manifest.json:
{
"name": "My App",
"short_name": "App",
"start_url": "/index.html",
"display": "standalone",
"icons": [
{
"src": "icon.png",
"sizes": "192x192",
"type": "image/png"
}
]
}Link it in your HTML:
<link rel="manifest" href="/manifest.json">Implementing dark mode in a web application can enhance user experience by providing a visually comfortable interface, especially in low-light environments. Here's how you can do it:
- Define Dark Mode Styles: Create a separate CSS file or define dark mode styles within your main CSS file.
- Toggle Dark Mode with JavaScript: Use JavaScript to toggle between light and dark modes.
- Persist User Preference: Save the user's preference in
localStorageso it persists across sessions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="toggle-dark-mode">Toggle Dark Mode</button>
<h1>Hello, World!</h1>
<p>This is an example of dark mode implementation.</p>
<script src="script.js"></script>
</body>
</html>body {
background-color: white;
color: black;
transition: background-color 0.3s, color 0.3s;
}
body.dark-mode {
background-color: black;
color: white;
}document.addEventListener('DOMContentLoaded', () => {
const toggleButton = document.getElementById('toggle-dark-mode');
const body = document.body;
// Load stored preference
const darkMode = localStorage.getItem('dark-mode');
if (darkMode === 'enabled') {
body.classList.add('dark-mode');
}
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');
if (body.classList.contains('dark-mode')) {
localStorage.setItem('dark-mode', 'enabled');
} else {
localStorage.removeItem('dark-mode');
}
});
});The picture element allows you to define multiple sources for an image, enabling responsive design by serving different images based on the viewport size or device pixel ratio.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Images with Picture Element</title>
</head>
<body>
<picture>
<source srcset="image-320w.jpg" media="(max-width: 320px)">
<source srcset="image-480w.jpg" media="(max-width: 480px)">
<source srcset="image-800w.jpg" media="(max-width: 800px)">
<img src="image-800w.jpg" alt="Responsive Image">
</picture>
</body>
</html><source>elements specify different images for various conditions.srcsetattribute defines the image URL.mediaattribute specifies the media query.<img>element provides a default image if none of the conditions are met.
A sticky header remains fixed at the top of the viewport as the user scrolls down the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky Header Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="sticky-header">
<h1>Sticky Header</h1>
</header>
<main>
<p>Content goes here...</p>
<!-- Add more content to enable scrolling -->
</main>
</body>
</html>.sticky-header {
position: sticky;
top: 0;
background-color: #333;
color: white;
padding: 10px;
z-index: 1000;
}position: sticky;makes the header stick to the top of the viewport.top: 0;ensures the header sticks to the top.z-index: 1000;keeps the header above other content.
HTML5 introduced several new input types to improve form usability and validation.
email: Validates email addresses.url: Validates URLs.tel: Input for telephone numbers.number: Input for numeric values.range: Input for selecting a value from a range.date: Input for date selection.time: Input for time selection.datetime-local: Input for selecting date and time.month: Input for selecting a month.week: Input for selecting a week.color: Input for color selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Input Types</title>
</head>
<body>
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="url">Website:</label>
<input type="url" id="url" name="url"><br><br>
<label for="tel">Phone Number:</label>
<input type="tel" id="tel" name="tel"><br><br>
<label for="number">Number:</label>
<input type="number" id="number" name="number"><br><br>
<label for="range">Range:</label>
<input type="range" id="range" name="range" min="0" max="100"><br><br>
<label for="date">Date:</label>
<input type="date" id="date" name="date"><br><br>
<label for="time">Time:</label>
<input type="time" id="time" name="time"><br><br>
<label for="datetime-local">Date and Time:</label>
<input type="datetime-local" id="datetime-local" name="datetime-local"><br><br>
<label for="month">Month:</label>
<input type="month" id="month" name="month"><br><br>
<label for="week">Week:</label>
<input type="week" id="week" name="week"><br><br>
<label for="color">Color:</label>
<input type="color" id="color" name="color"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>Internationalization (i18n) is the process of designing a web application to support multiple languages and regions.
- Use Unicode: Ensure your application supports Unicode.
- Locale-Specific Content: Create content files for each locale.
- Language Switcher: Provide a mechanism to switch languages.
- External Libraries: Use libraries like i18next for managing translations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internationalization Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<select id="language-switcher">
<option value="en">English</option>
<option value="es">Español</option>
</select>
<h1 id="greeting">Hello, World!</h1>
<script src="i18next.min.js"></script>
<script src="script.js"></script>
</body>
</html>const resources = {
en: {
translation: {
"greeting": "Hello, World!"
}
},
es: {
translation: {
"greeting": "¡Hola, Mundo!"
}
}
};
i18next.init({
lng: 'en',
resources
}, (err, t) => {
if (err) return console.error(err);
document.getElementById('greeting').textContent = t('greeting');
});
document.getElementById('language-switcher').addEventListener('change', (event) => {
const lng = event.target.value;
i18next.changeLanguage(lng, (err, t) => {
if (err) return console.error(err);
document.getElementById('greeting').textContent = t('greeting');
});
});Progressive Web Apps (PWAs) are web applications that use modern web technologies to deliver app-like experiences to users.
- Offline Capabilities: Work offline using service workers.
- Installable: Can be installed on the user's device like native apps.
- Responsive: Adapt to various screen sizes and orientations.
- Fast Loading: Load quickly even on slow networks.
- Secure: Served over HTTPS to ensure security.
{
"name": "PWA Example",
"short_name": "PWA",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('pwa-cache').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/script.js',
'/icon-192x192.png',
'/icon-512x512.png'
]);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PWA Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="manifest" href="/manifest.json">
</head>
<body>
<h1>Progressive Web App Example</h1>
<p>This is a simple PWA example.</p>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
}).catch((error) => {
console.log('Service Worker registration failed:', error);
});
}
</script>
</body>
</html>Creating an accessible modal dialog involves ensuring that the dialog is keyboard-navigable and screen-reader friendly.
- HTML Structure: Use semantic HTML and ARIA roles.
- CSS Styling: Style the modal and overlay.
- JavaScript: Manage focus and accessibility.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accessible Modal Dialog Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="open-modal">Open Modal</button>
<div id="modal" class="modal" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-content">
<h2 id="modal-title">Modal Title</h2>
<p>This is an accessible modal dialog.</p>
<button id="close-modal">Close</button>
</div>
</div>
<div id="overlay" class="overlay" aria-hidden="true"></div>
<script src="script.js"></script>
</body>
</html>.modal, .overlay {
display: none;
}
.modal[aria-hidden="false"], .overlay[aria-hidden="false"] {
display: block;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
}document.addEventListener('DOMContentLoaded', () => {
const openModalButton = document.getElementById('open-modal');
const closeModalButton = document.getElementById('close-modal');
const modal = document.getElementById('modal');
const overlay = document.getElementById('overlay');
openModalButton.addEventListener('click', () => {
modal.setAttribute('aria-hidden', 'false');
overlay.setAttribute('aria-hidden', 'false');
closeModalButton.focus();
});
closeModalButton.addEventListener('click', () => {
modal.setAttribute('aria-hidden', 'true');
overlay.setAttribute('aria-hidden', 'true');
openModalButton.focus();
});
});CSS Grid is a powerful layout system that allows you to create complex grid-based layouts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Grid Layout Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="grid-container">
<div class="item item1">Item 1</div>
<div class="item item2">Item 2</div>
<div class="item item3">Item 3</div>
<div class="item item4">Item 4</div>
<div class="item item5">Item 5</div>
<div class="item item6">Item 6</div>
</div>
</body>
</html>.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.item {
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}display: grid;enables grid layout.grid-template-columns: repeat(3, 1fr);creates three equal-width columns.gap: 10px;sets the gap between grid items.
The Content-Security-Policy (CSP) header is a security feature that helps prevent various types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.
- Prevents XSS Attacks: Restricts the sources of script content.
- Mitigates Data Injection Attacks: Limits the sources of data that can be loaded.
- Protects Against Clickjacking: Controls which sites can embed your content.
Content-Security-Policy: default-src 'self'; img-src https://example.com; script-src 'self' https://apis.example.com
default-src 'self';allows content only from the same origin.img-src https://example.com;allows images fromexample.com.script-src 'self' https://apis.example.com;allows scripts from the same origin andapis.example.com.
CSS custom properties, also known as CSS variables, are entities defined by CSS authors that contain specific values to be reused throughout a document. They can make your CSS more maintainable and easier to read.
To create a CSS custom property, you use the -- prefix followed by the property name. Custom properties are usually defined within a :root selector so they can be accessed anywhere in the document.
:root {
--main-bg-color: #3498db;
--main-text-color: #ffffff;
--spacing: 16px;
}In this example:
--main-bg-coloris a custom property for the primary background color.--main-text-coloris a custom property for the text color.--spacingis a custom property for spacing.
To use a custom property, you use the var() function.
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
padding: var(--spacing);
}In this example:
background-coloris set to the value of--main-bg-color.coloris set to the value of--main-text-color.paddingis set to the value of--spacing.
Here is a complete example demonstrating how to create and use CSS custom properties in an HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Custom Properties Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
<main>
<p>This is a paragraph with main text color and spacing.</p>
</main>
<footer>
<p>Footer content here.</p>
</footer>
</body>
</html>:root {
--main-bg-color: #3498db;
--main-text-color: #ffffff;
--secondary-bg-color: #2ecc71;
--secondary-text-color: #333333;
--spacing: 16px;
}
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
padding: var(--spacing);
margin: 0;
font-family: Arial, sans-serif;
}
header {
background-color: var(--secondary-bg-color);
color: var(--secondary-text-color);
padding: var(--spacing);
text-align: center;
}
main {
padding: var(--spacing);
}
footer {
background-color: var(--secondary-bg-color);
color: var(--secondary-text-color);
padding: var(--spacing);
text-align: center;
}-
Defining Custom Properties:
- Custom properties are defined within the
:rootpseudo-class. This is a special selector that matches the document’s root element and allows you to define global variables. - Each custom property is prefixed with
--.
- Custom properties are defined within the
-
Using Custom Properties:
- The
var()function is used to retrieve the value of a custom property. - Custom properties can be used in any CSS property.
- The
-
Benefits:
- Reusability: Custom properties can be reused throughout your CSS, reducing redundancy.
- Maintainability: Changes to custom properties automatically propagate to all instances where they’re used.
- Dynamic Styling: Custom properties can be updated dynamically using JavaScript for responsive or interactive designs.
-
Fallback Values:
- You can provide a fallback value for
var(), in case the custom property is not defined.
- You can provide a fallback value for
body {
background-color: var(--main-bg-color, #000000);
}In this example, if --main-bg-color is not defined, #000000 will be used as the background color.
CSS custom properties (variables) are a powerful feature for managing and maintaining your styles efficiently. By understanding how to create and use them, you can write more modular and scalable CSS.