HTML5 has significantly transformed web development by introducing new features and enhanced elements that cater to the demands of modern, interactive, and user-focused websites.
These features include embedded multimedia capabilities and powerful APIs. HTML5 optimizes websites for speed, functionality, and a seamless user experience, eliminating the need for additional plugins and enhancing cross-device compatibility.
This evolution has improved website performance and paved the way for creating dynamic and highly responsive web applications.
Understanding these HTML5 features is crucial for developers aiming to build applications that engage users across various devices and browsers.
Enrol in one of our software engineering courses, and within 8 months; you will be ready to apply and work for an international software company, tripling your income.
What is HTML5?
HTML5 is the fifth iteration of the Hypertext Markup Language (HTML). It is a comprehensive update that supports the latest web standards, multimedia elements, and accessibility requirements.
These are needed for creating interactive and user-friendly websites. HTML5 was developed with modern web demands in mind. It allows developers to directly incorporate rich multimedia, complex animations, and responsive content into websites without relying on third-party plugins.
Evolution from Previous Versions:
HTML5 emerged as a solution to limitations in HTML4, released in 1997 when web content was relatively simple. With the advent of more dynamic, multimedia-rich applications, HTML5 introduced significant upgrades to meet these demands
12 New HLTM5 Features for 2025
Below are 12 new HTML5 features that were introduced to make the lives of software developers easy.
1. Semantic Elements for Structured Content
Explanation:
HTML5 introduced a set of new semantic elements, including <header>, <footer>, <section>, and <article>, which play a crucial role in organizing content. These tags are more descriptive than traditional <div> elements, making it easier for developers and browsers to understand the structure and purpose of various sections within a web page. For instance:
- <header> typically contains introductory content or navigation links.
- <footer> holds contact information or links at the end of a section or page.
- <section> groups related content, providing a way to break down complex information into manageable segments.
- <article> designates standalone content that can be independently distributed, like blog posts or news stories.
These semantic tags help in creating a logical and consistent content structure, enhancing the overall readability and accessibility of web pages.
2. The Canvas Element for Graphics
The <canvas> element in HTML5 is a powerful feature that enables the rendering of 2D graphics, animations, and interactive elements directly within a webpage.
Acting as a drawable region defined by height and width, <canvas> allows developers to create dynamic, high-quality graphics by drawing shapes, lines, and images.
It provides a “drawing surface” controlled with JavaScript, making it versatile for various applications and eliminating the need for additional plugins.
Use Cases:
The <canvas> element is commonly used in web applications that require interactive visual content. Some famous use cases include:
- Rendering Charts and Data Visualizations: <canvas> is often used in data-intensive applications for creating visualizations like line charts, bar graphs, and pie charts.
- Game Development: Game developers leverage <canvas> to create browser-based games with real-time animations, interactive characters, and visual effects.
- Animation and Image Processing: It directly enables animations such as image slideshows, complex animations, and image editing tools in the browser.
With its flexibility, <canvas> enhances user engagement through rich graphical content, paving the way for highly interactive web experiences.
Code Example: Basic Rectangle on Canvas
The following example demonstrates creating a simple element and drawing a blue rectangle using JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Canvas Example</title> </head> <body>
<!-- Canvas Element -->
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;"></canvas>
<script>
// Accessing the canvas element and its 2D context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Drawing a blue rectangle
context.fillStyle = "#0000FF";
// Set fill color to blue
context.fillRect(50, 50, 150, 100);
// Draw rectangle: x, y, width, height
</script>
</body>
</html>
Explanation of the Code
- The <canvas> element with id=”myCanvas” is defined with a width and height of 400×200 pixels.
- We retrieve the canvas element using JavaScript and then access its 2D drawing context.
- We set the fill color to blue using context.fillStyle = “#0000FF”; draw a rectangle with context on the canvas.fillRect(50, 50, 150, 100);, where (50, 50) is the starting position, and 150×100 represents the width and height of the rectangle.
3. Geolocation API for Location-Based Services
The HTML5 Geolocation API enables developers to access a user’s geographical location, which can be used to personalize content and enhance the user experience.
By obtaining location data, software developers can provide local weather forecasts, nearby stores, location-based advertisements, or real-time navigation.
Privacy and User Consent:
Because location data is sensitive, the Geolocation API requires explicit permission from the user. When a website requests location data, the browser prompts the user to allow or deny access, ensuring privacy and giving users control over their data.
Code Example: Getting User’s Location
The following example demonstrates how to use the Geolocation API to get a user’s current latitude and longitude and display them on the web page.
Explanation of the Code:
- The getLocation() function checks if the Geolocation API is supported in the browser. If so, the API requests the user’s current position with navigator.geolocation.getCurrentPosition().
- If the request is successful, the showPosition() function retrieves the latitude and longitude and displays them in the locationOutput paragraph.
- If there’s an error (e.g., the user denies permission), showError() provides a user-friendly message based on the error code.
4. Local Storage and Session Storage for Offline Data
HTML5 provides two methods for client-side storage within the user’s browser: localStorage and sessionStorage. Both allow web applications to store data that can be accessed later, even without an internet connection, but they differ in data persistence:
- localStorage: Stores data with no expiration date, meaning it remains available until the user manually deletes it or clears the browser cache.
- sessionStorage: Stores data only for the duration of the page session. Once the browser or tab is closed, the stored data is removed.
Advantages Over Cookies:
Compared to cookies, localStorage and sessionStorage offer:
- Larger storage capacity (typically around 5-10 MB compared to the 4 KB limit of cookies).
- No need for network requests since they are accessed directly within the browser.
- Simpler API for setting, getting, and removing data.
Code Example: Storing and Retrieving Data with localStorage and sessionStorage
The following example demonstrates how to use both localStorage and sessionStorage to save and retrieve user preferences within the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Local and Session Storage Example</title>
</head>
<body>
<h2>Save User Preferences</h2>
<button onclick="savePreferences()">Save Preferences to Local Storage</button>
<button onclick="saveSessionData()">Save Session Data</button>
<button onclick="retrieveData()">Retrieve Data</button>
<p id="output"></p>
<script>
// Function to save data to localStorage
function savePreferences() {
localStorage.setItem("theme", "dark");
localStorage.setItem("fontSize", "16px");
document.getElementById("output").innerHTML = "Preferences saved to localStorage.";
}
// Function to save data to sessionStorage
function saveSessionData() {
sessionStorage.setItem("sessionData", "Session active");
document.getElementById("output").innerHTML = "Data saved to sessionStorage.";
}
// Function to retrieve and display data from storage
function retrieveData() {
const theme = localStorage.getItem("theme");
const fontSize = localStorage.getItem("fontSize");
const sessionData = sessionStorage.getItem("sessionData");
document.getElementById("output").innerHTML =
"Theme: " + (theme || "Not Set") + "<br>" +
"Font Size: " + (fontSize || "Not Set") + "<br>" +
"Session Data: " + (sessionData || "Not Set");
}
</script>
</body>
</html>
Explanation of the Code:
- Saving Data:
- The savePreferences() function saves a theme and fontSize preference to localStorage, which persists even if the browser is closed and reopened.
- The saveSessionData() function stores session-specific information in sessionStorage, which lasts only while the page session is active.
- Retrieving Data:
- The retrieveData() function gets the stored data from both localStorage and sessionStorage. It displays “Not Set” as a fallback if the data isn’t found.
5. Form Enhancements for Improved User Input
HTML5 introduced new form input types and validation attributes that make capturing and validating user data more easily. These input types, such as <date>, <email>, <range>, and <color>, provide native support for common data formats, reducing the need for custom JavaScript validation. HTML5 form validation attributes like required, min, max, and pattern further improve the reliability of user data by validating inputs directly in the browser.
Benefits:
These enhanced input types and validation attributes simplify the data entry process for users, improving accuracy and reducing frustration. They also help developers ensure that submitted data meets specific criteria without requiring complex validation scripts.
Code Example: Enhanced HTML5 Form Inputs
The following example showcases a form with various HTML5 input types and validation attributes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Form Enhancements</title>
</head>
<body>
<h2>User Information Form</h2>
<form action="/submit" method="POST">
<!-- Email input with built-in validation -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required placeholder="you@example.com">
<br><br>
<!-- Date input for selecting birth date -->
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
<br><br>
<!-- Range input for setting age preference -->
<label for="age">Age Preference (18-60):</label>
<input type="range" id="age" name="age" min="18" max="60" value="30">
<br><br>
<!-- Color picker input -->
<label for="favColor">Favorite Color:</label>
<input type="color" id="favColor" name="favColor">
<br><br>
<!-- Submit button -->
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation of the Code:
- Email Input: The type=”email” input field only accepts valid email formats, and the required attribute ensures that the user provides an email address before submitting the form.
- Date Input: The type=”date” input displays a date picker in supported browsers, allowing users to select a date (e.g., for entering a birth date).
- Range Input: The type=”range” input provides a slider, allowing users to choose a value between a specified minimum and maximum (e.g., age preference).
- Color Picker Input: The type=”color” input opens a color picker tool, allowing users to select a color visually rather than entering a hex code.
6. The Drag-and-Drop API for Interactive Interfaces
The HTML5 Drag-and-Drop API allows developers to create more interactive web applications by enabling users to drag and drop elements within a webpage. This functionality enhances user experience by providing intuitive ways to interact with content, making it easy for users to manipulate elements visually.
The API includes methods for dragging items, handling the drop action, and managing the transferred data.
Examples:
Common use cases for the Drag-and-Drop API include:
- File Uploads: Users can drag files from their computer directly into a web application to upload them, improving convenience and speed.
- Rearranging Elements: Users can reorder items in lists or galleries by dragging and dropping, allowing for more dynamic user interfaces.
Code Example: Basic Drag-and-Drop Functionality
The following example demonstrates a simple implementation of the Drag-and-Drop API to rearrange items in a list.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag-and-Drop Example</title>
<style>
.draggable {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
background-color: #f9f9f9;
cursor: move;
}
.over {
border: 2px dashed #007bff;
}
</style>
</head>
<body>
<h2>Drag-and-Drop List</h2>
<div id="itemList">
<div class="draggable" draggable="true">Item 1</div>
<div class="draggable" draggable="true">Item 2</div>
<div class="draggable" draggable="true">Item 3</div>
<div class="draggable" draggable="true">Item 4</div>
</div>
<script>
// Select all draggable items
const draggables = document.querySelectorAll('.draggable');
// Add event listeners to each draggable item
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging');
});
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging');
});
});
// Select the list container
const itemList = document.getElementById('itemList');
// Add event listeners for dragover and drop
itemList.addEventListener('dragover', (event) => {
event.preventDefault(); // Prevent default behavior to allow drop
const dragging = document.querySelector('.dragging');
itemList.insertBefore(dragging, event.target); // Insert dragged item
});
itemList.addEventListener('drop', (event) => {
event.preventDefault();
const dragging = document.querySelector('.dragging');
itemList.insertBefore(dragging, event.target); // Finalize drop
});
</script>
</body>
</html>
Explanation of the Code:
- Draggable Items: Each item in the list has the draggable=”true” attribute, allowing it to be dragged. The .draggable class adds some basic styles to these items.
- Drag Events:
- dragstart: The dragging class is added for styling when an item is dragged.
- dragend: When the drag operation ends, the dragging class is removed.
- Drop Functionality:
- The dragover event allows dropping by calling event.preventDefault(). When an item is dragged over another, it will insert the dragging item before the target element.
- The drop event finalizes the action by inserting the dragged item into its new position in the list.
7. Web Workers for Background Processing
Web Workers are a powerful feature in HTML5 that enable the execution of JavaScript code in the background, separate from the main thread of a web application.
This means that heavy computational tasks can be processed without blocking the user interface, leading to smoother and more responsive web applications. By offloading work to a worker thread, developers can ensure that the main thread remains available for user interactions, maintaining a seamless user experience.
Use Cases:
Web Workers are beneficial in scenarios where performance is crucial, including:
- Data Processing: Handling large datasets, such as parsing JSON or performing complex calculations, without freezing the UI.
- Real-Time Updates: Fetching real-time data from APIs or WebSocket connections while allowing users to interact with the interface without delays.
- High-Performance Tasks: Running tasks like image processing, video encoding, or CPU-intensive operations require significant computation time.
Code Example: Using Web Workers
Below is a simple example demonstrating how to create a Web Worker to perform a time-consuming calculation (e.g., calculating the factorial of a number) without freezing the main thread.
main.js (Main thread)
// Create a new Web Worker
const worker = new Worker('worker.js');
// Listen for messages from the worker
worker.onmessage = function(event) {
console.log('Result from worker:', event.data);
};
// Send a number to the worker to calculate its factorial
worker.postMessage(10); // Change this number to test with different values
worker.js (Web Worker)
// Listen for messages from the main thread
onmessage = function(event) {
const number = event.data;
const result = factorial(number);
postMessage(result); // Send the result back to the main thread
};
// Function to calculate factorial
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Explanation of the Code:
- Main Thread (main.js):
- A new Web Worker is created using new Worker(‘worker.js’), specifying the JavaScript file that contains the worker’s code.
- The main thread listens for messages from the worker using worker.onmessage, which allows it to receive and process the results sent back from the worker.
- A number (in this case, 10) is sent to the worker for processing via worker.postMessage(10).
- Web Worker (worker.js):
- The worker listens for incoming messages using onmessage. When it receives a message (in this case, a number), it calculates the factorial of that number using the factorial function.
- Once the calculation is complete, the result is sent back to the main thread using postMessage(result).
8. WebSocket API for Real-Time Communication
The WebSocket API is a powerful feature of HTML5 that facilitates two-way, real-time communication between clients and servers.
Unlike traditional HTTP requests, which follow a request-response model, WebSocket enables persistent connections, sending and receiving data instantly without the overhead of establishing new connections for each interaction.
This efficiency is crucial for applications that require real-time updates and responsiveness.
Key Features of WebSocket:
- Full-Duplex Communication: WebSocket allows simultaneous data transfer in both directions (client to server and server to client), providing a seamless communication experience.
- Reduced Latency: The persistent connection reduces the delay associated with establishing new HTTP connections, enabling faster data transmission.
- Efficient Use of Resources: WebSockets use a single, long-lived connection, which minimizes network overhead and improves scalability.
Practical Applications: WebSocket technology has a wide range of applications, including:
- Live Chat Applications: Instant messaging and chat systems can use WebSocket to provide real-time messaging capabilities, allowing users to communicate without delay.
- Real-Time Notifications: Applications can push updates, alerts, and notifications to users as they occur, enhancing user engagement and experience.
- Online Gaming: Multiplayer games can use WebSocket for real-time interaction between players, ensuring smooth gameplay and immediate feedback.
Code Example: Implementing a Basic WebSocket Client
The following example demonstrates creating a simple WebSocket client that connects to a server and sends/receives messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Example</title>
</head>
<body>
<h2>WebSocket Real-Time Communication</h2>
<input type="text" id="messageInput" placeholder="Type a message">
<button id="sendButton">Send</button>
<div id="messages"></div>
<script>
// Create a new WebSocket connection
const socket = new WebSocket('ws://localhost:8080'); // Change the URL to your server
// When the connection is open, log a message
socket.onopen = function() {
console.log('WebSocket connection established');
};
// Listen for messages from the server
socket.onmessage = function(event) {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += `<p>Received: ${event.data}</p>`; // Display the received message
};
// Send a message when the button is clicked
document.getElementById('sendButton').onclick = function() {
const input = document.getElementById('messageInput');
socket.send(input.value); // Send the message to the server
input.value = ''; // Clear the input field
};
// Handle errors
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
// Handle connection closure
socket.onclose = function() {
console.log('WebSocket connection closed');
};
</script>
</body>
</html>
Explanation of the Code:
- WebSocket Connection: A new WebSocket connection is established using new WebSocket(‘ws://localhost:8080’). The URL should point to a WebSocket server.
- Connection Events:
- onopen: Logs a message when the connection is successfully established.
- onmessage: Listens for incoming messages from the server. When a message is received, it is displayed in the messages div.
- onerror: Captures any errors that occur during the WebSocket communication.
- onclose: Logs a message when the WebSocket connection is closed.
- Sending Messages: When the user types a message and clicks the “Send” button, the message is sent to the server using socket.send(input.value), and the input field is cleared.
9. Improved Accessibility Features
HTML5 strongly emphasizes accessibility, ensuring that web content is usable by everyone, including people with disabilities.
Improved accessibility features allow developers to create websites that can be navigated and understood by users with various disabilities. This is essential not only for inclusivity but also for compliance with accessibility standards and regulations.
Key Features for Improved Accessibility:
- Semantic Elements: HTML5 introduces semantic elements like <header>, <footer>, <article>, and <section> that provide meaningful context and structure to the content, making it easier for screen readers and assistive technologies to interpret.
- ARIA Attributes: Accessible Rich Internet Applications (ARIA) attributes enhance the accessibility of HTML5 elements, notably when standard HTML lacks semantic meaning. These attributes help define roles, properties, and states of UI elements, improving the experience for users of assistive technologies.
Examples of ARIA Attributes:
- aria-label: Provides an accessible name for an element useful for form controls or icons without text labels.
- aria-hidden: Indicates whether an element should be hidden from assistive technologies, allowing developers to control visibility.
- aria-live: Allows developers to specify how updates to the content should be announced by screen readers, which is useful for dynamic content updates.
Code Example: Using ARIA Attributes
Below is an example demonstrating using ARIA attributes to improve accessibility in a simple HTML5 form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accessible Form Example</title>
</head>
<body>
<h1>Contact Us</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name" aria-label="Enter your full name" required>
<label for="email">Email:</label>
<input type="email" id="email" aria-label="Enter your email address" required>
<label for="message">Message:</label>
<textarea id="message" aria-label="Type your message here" required></textarea>
<button type="submit">Submit</button>
</form>
<div role="alert" aria-live="polite" id="feedback"></div>
<script>
// Simple form submission feedback
const form = document.querySelector('form');
const feedback = document.getElementById('feedback');
form.onsubmit = function(event) {
event.preventDefault(); // Prevent actual form submission for demo
feedback.textContent = 'Thank you for your message!'; // Provide feedback
};
</script>
</body>
</html>
Explanation of the Code:
- Form Structure: The form includes fields for name, email, and a message. Each input field is associated with a <label> that enhances accessibility.
- ARIA Attributes:
- Each input field uses aria-label to provide a clear description, ensuring that screen readers can convey the purpose of the field to users.
- The role=”alert” on the feedback div indicates that it is an alert region, and aria-live=”polite” informs assistive technologies that updates to this element should be announced without interrupting the user.
- JavaScript Feedback: A simple script captures form submissions to provide feedback to the user, demonstrating how real-time updates can be communicated through the accessibility features.
10. Responsive Design with Media Queries
Media queries are a fundamental feature of HTML5 and CSS3 that enable responsive web design by allowing developers to apply styles based on the device’s characteristics, such as screen size, resolution, and orientation.
This capability is essential for creating websites that provide an optimal viewing experience across various devices, from desktop computers to smartphones and tablets.
How Media Queries Work: Media queries use the @media rule in CSS to define different styles for various conditions. Developers can specify breakpoints at which the layout or design of the website should change. For example, styles can be applied specifically for devices with a maximum width of 768 pixels, which is typical for tablets.
Basic Syntax of a Media Query:
@media (max-width: 768px) {
/* Styles for devices with a maximum width of 768px */
body {
background-color: lightblue;
}
.container {
flex-direction: column; /* Change layout for smaller screens */
}
}
SEO and User Experience Benefits:
- Mobile-Friendliness: Search engines, notably Google, prioritize mobile-friendly websites in their rankings. Responsive design ensures that users have a consistent experience across devices, which can lead to lower bounce rates and higher engagement.
- Enhanced User Experience: By optimizing the layout and content for different screen sizes, users can easily navigate and interact with the website, improving overall satisfaction and accessibility.
- Faster Load Times: A responsive design typically results in fewer resources being loaded on smaller devices, which can enhance page load speed—a critical factor for both user experience and SEO.
Code Example: Using Media Queries for Responsive Design
Below is an example demonstrating how to use media queries to create a responsive layout for a simple web page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Design Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
display: flex;
flex-wrap: wrap;
padding: 20px;
background-color: #f4f4f4;
}
.box {
flex: 1 1 300px; /* Base size of 300px, can grow or shrink */
margin: 10px;
padding: 20px;
background-color: #4CAF50;
color: white;
text-align: center;
}
/* Media query for devices with a maximum width of 768px */
@media (max-width: 768px) {
.container {
flex-direction: column; /* Stack boxes vertically */
}
.box {
margin: 5px 0; /* Reduce margin for stacked layout */
}
}
</style>
</head>
<body>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
</body>
</html>
Explanation of the Code:
- Basic Structure: The HTML includes a simple flex container with three boxes.
- Flexbox Layout: The .container class uses flexbox to arrange the .box elements in a row. Each box has a base width of 300 pixels and can grow or shrink based on the available space.
- Media Query:
- The media query activates when the viewport width is 768 pixels or less.
- Inside the media query, the flex-direction is changed to a column, stacking the boxes vertically for smaller screens.
- Margins are adjusted to enhance the appearance of the stacked layout.
11. Native SVG Support for Scalable Graphics
HTML5 provides native support for Scalable Vector Graphics (SVG), a powerful tool for creating high-quality vector graphics that can be scaled to any size without losing quality.
Unlike raster images (e.g., JPEG, PNG), SVG images are defined in XML format and can be manipulated with CSS and JavaScript. This feature allows developers to create resolution-independent graphics that are perfect for modern web applications, enhancing aesthetics and performance.
Benefits of Using SVG in HTML5:
- Scalability: SVG graphics maintain quality at any resolution, making them ideal for responsive design. SVG images remain sharp and clear whether viewed on a small mobile screen or a large desktop monitor.
- Improved Load Times: SVG files are often smaller than raster images, especially for graphics composed of simple shapes. This can lead to faster load times, improving user experience and overall site performance.
- Interactivity and Animation: SVG can be styled and animated using CSS and JavaScript, allowing for rich interactivity that enhances user engagement.
- Accessibility: Since SVG is XML-based, text elements within SVG graphics can be indexed by search engines and read by screen readers, improving accessibility.
Code Example: Using SVG in HTML5
Below is an example demonstrating SVG’s use to create a simple graphic within an HTML5 document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
svg {
width: 80%; /* Responsive width */
height: auto; /* Maintain aspect ratio */
}
</style>
</head>
<body>
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="lightblue" />
<rect x="20" y="20" width="60" height="60" fill="lightgreen" />
<text x="50%" y="50%" font-size="10" text-anchor="middle" fill="darkblue" dy=".3em">SVG Example</text>
</svg>
</body>
</html>
Explanation of the Code:
- SVG Structure: The SVG element is defined with a viewBox that determines the coordinate system for the graphic.
- Shapes:
- A <circle> element creates a circle centered at (50, 50) with a radius of 40 units, filled with light blue.
- A <rect> element creates a square positioned at (20, 20) with a width and height of 60 units, filled with light green.
- A <text> element displays the “SVG Example” text centered within the SVG.
- Responsive Design: The SVG element is styled to be 80% of the viewport width, maintaining its aspect ratio with height: auto.
To fully harness the potential of HTML5, we encourage developers to continue their learning journey. Explore additional resources, tutorials, and hands-on projects to deepen your understanding and skill set in HTML5.
By staying updated on the latest trends and best practices in web development, you can ensure that your websites remain competitive and user-friendly in an ever-evolving digital landscape. Start your exploration today and unlock the full power of HTML5 for your projects!