- 👤 Andrés Cruz
The Definitive HTML5 Guide: From Forms and Semantics to Advanced Graphics APIs
HTML5 is much more than a simple markup language for structuring web documents. It is a robust and powerful application platform, equipped with an arsenal of semantic tags, advanced form controls, and a set of JavaScript APIs that allow for the creation of interactive and media-rich experiences, previously only possible with external plugins like Flash.
At DesarrolloLibre, we've broken down each of these features to showcase their true potential.
This pillar guide is the consolidation of that knowledge. We'll take you on a journey that starts with the fundamental structure of a document, exploring elements often overlooked.
We'll delve into creating modern and accessible forms with native validation. Then, we'll immerse ourselves in the graphical heart of HTML5, with exhaustive guides on the Canvas API for pixel-level image manipulation and the creation of scalable vector graphics with SVG.
Finally, we'll explore the APIs that provide our applications with advanced interactivity, such as Drag and Drop. Prepare to rediscover HTML5, not as a language learned once, but as a constantly evolving development platform.
HTML5 Form Fields
In this article I will try to show you the new fields that HTML5 brings us; as we will see, there are many specific "type" values for each field type; ranging from various date formats to others like email, URLs, ranges, among others:
| Type | Description | Syntax | HTML Markup |
|---|---|---|---|
| Date | Date format encompassing day-month-year. | <input type="date"> | |
| datetime | Date and time using UTC - time zone. | <input type="datetime"> | |
| datetime-local | Date and time without time zone. | <input type="datetime-local"> | |
| month | Month and year. | <input type="month"> | |
| time | The time of day. | <input type="time"> | |
| week | Format for entering the week of the year. | <input type="week"> | |
| color | A "color picker", using hexadecimal notation. | <input type="color""> | |
| Field for entering an email; using the format followed by the pattern attribute. | <input type="email"> | ||
| tel | Field for entering a phone number; using the format followed by the pattern attribute. | <input type="tel"> | |
| search | A search field. | <input type="search"> | |
| range | A 'slider' for numbers. | <input type="range"> | |
| number | Only accepts numeric values. | <input type="number"> | |
| url | Only accepts URL. | <input type="url"> |
Section 1: Structure and Fundamental Elements
Every great building starts with solid foundations. On the web, those foundations are the HTML tags that structure our content. Beyond divs and spans, HTML offers a rich semantic vocabulary that, when used correctly, improves accessibility, SEO, and the maintainability of our code. In this section, we'll review basic elements and discover some lesser-known but incredibly useful tags.
Essential Tags: Paragraphs and Line Breaks
The <p> Element
The <p> element is the fundamental building block for text. It defines a paragraph, which is a block of text that is visually separated from others. Although it seems simple, it's important to use it correctly.
- Correct Use: To group text into logical units. Browsers automatically add a margin between paragraphs.
- Misuse: An empty paragraph (
<p>) should not be used solely to create vertical space. For that, CSS (marginorpadding) should be used. Neither should block elements likedivorh1be nested inside a<p>.
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>
<p> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> Delve into the correct use and styles of the paragraph tag in our Quick guide about the p element in HTML.
The <br> Element
The <br> element forces a line break within a block of text, such as a paragraph or a heading. It is an "empty" tag, meaning it has no content or closing tag in HTML. However, for XHTML compatibility, it is often written as <br />.
Its use should be for line breaks that are an intrinsic part of the content, such as in poems or postal addresses, and not for creating visual separation between elements.
<p>DesarrolloLibre<br> Fake Street 123<br> Web City, Internet</p> Learn more about this simple but important element in our Quick guide about the br element in HTML.
Uncommon but Useful Elements
<base>: Defining a Base URL for Links
The <base> element is a unique tag placed in the head of a document that allows defining a base URL and/or a default target for all relative links on the page. This is especially useful on sites with a complex directory structure or in single-page applications (SPAs).
<head> <base href="https://www.desarrollolibre.net/blog/" target="_blank"> </head> <body> <!-- This link will open "https://www.desarrollolibre.net/blog/html/" in a new tab --> <a href="html/">HTML Section</a> </body> <abbr>: Clarifying Abbreviations
The <abbr> tag is used to mark abbreviations or acronyms. The title attribute is used to provide the full expansion, which most browsers display as a *tooltip* when hovering over the text.
<p>I love writing code in <abbr title="HyperText Markup Language">HTML</abbr>.</p> <map> and <area>: Creating Image Maps
These tags allow defining clickable areas within a single image. The <map> element acts as a container for one or more <area> tags, each of which defines a shape (rectangle, circle, or polygon) and a link.
<img src="planetas.gif" width="145" height="126" alt="Planets" usemap="#planetmap"> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" href="sol.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercurio.htm" alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map> Learn to create your own image maps in: The area and map element in HTML.
Section 2: Advanced HTML5 Forms
HTML5 revolutionized web forms, introducing a large number of new input types and attributes that allow for native client-side validations, improving the user experience and reducing the dependency on JavaScript for common tasks.
New input Types
HTML5 expanded the type attribute of the input element to include specific controls for different data types. This not only provides better semantics, but on mobile devices often activates keyboards optimized for that input.
date,time,datetime-local,month,week: Display native browser date/time selectors.color: Displays a native color picker.email: Validates that the input is in an email format.tel: For phone numbers (activates the numeric keypad on mobile).url: Validates that the input is a URL.number: A field for numbers, with controls to increment/decrement.range: A slider control for selecting a value within a range.search: A stylized text field for searches.
<label for="fecha-cita">Appointment Date:</label> <input type="date" id="fecha-cita" name="cita"> <label for="cantidad">Quantity (between 1 and 5):</label> <input type="number" id="cantidad" name="cantidad" min="1" max="5"> For numeric fields, you can use the step attribute to control granularity. For example, for a price field that accepts two decimals, step="0.01" is used.
Native Validation with the pattern Attribute
For more complex validations not covered by the new input types, HTML5 introduced the pattern attribute. This attribute allows you to specify a regular expression that the field's value must match to be valid.
This is extremely powerful for validating specific formats, such as postal codes, phone numbers, or usernames, without writing a single line of JavaScript.
<!-- Validates a 5-digit postal code --> <label for="codigopostal">Postal Code:</label> <input type="text" id="codigopostal" name="codigopostal" pattern="[0-9]{5}" title="Must contain 5 numeric digits"> The title attribute is important here, as its content is displayed to the user as an error message if the validation fails. It is crucial to remember that client-side validation is a user aid, but never a substitute for server-side validation.
Master validation with regular expressions in: The pattern attribute for form validation.
Autocomplete Suggestions with <datalist>
The <datalist> element provides a list of predefined options for an input element, which the browser displays as autocomplete suggestions as the user types.
It is linked to an input through the input's list attribute, which must match the <datalist>'s id.
<label for="navegador">Preferred Browser:</label> <input list="navegadores" id="navegador" name="navegador"> <datalist id="navegadores"> <option value="Chrome"> <option value="Firefox"> <option value="Safari"> <option value="Edge"> </datalist> Unlike a <select>, the user is not limited to the options in the list and can type their own value.
Learn to use datalists in: The datalist element in HTML5.
Submission Control with formaction
Sometimes, a form needs to have several submit buttons that perform different actions (e.g., "Save Draft" vs. "Publish"). Instead of using JavaScript to change the form's action attribute, you can use the formaction attribute directly on the submit button.
formaction overrides the form's action only for that specific button.
<form action="/save-draft" method="post"> <textarea name="contenido"></textarea> <button type="submit">Save Draft</button> <button type="submit" formaction="/publish">Publish Now</button> </form>There are also the formenctype, formmethod, formnovalidate, and formtarget attributes that work in the same way, overriding the corresponding form attributes.
Discover this useful attribute in: The formAction attribute in HTML.
Section 3: Native Multimedia and Graphics
HTML5 transformed the web from a text-based medium to a complete multimedia platform. With the introduction of the <video> and <audio> tags, and the powerful <canvas> and <svg> APIs, developers gained the tools to create rich visual and graphic content experiences directly in the browser, without relying on third-party plugins.
Native Video and Audio
The <video> and <audio> tags allow for the semantic embedding of multimedia content.
<video width="640" height="360" controls poster="poster.jpg"> <source src="video.mp4" type="video/mp4"> <source src="video.webm" type="video/webm"> Your browser does not support the video element. </video> Key attributes:
controls: Displays native browser playback controls.autoplay: Starts playback automatically (often requiresmutedin modern browsers).loop: Repeats the video/audio upon completion.poster: Displays an image before the video starts playing.
The use of multiple <source> tags is crucial for cross-browser compatibility, as not all browsers support the same video formats (MP4, WebM, Ogg).
For content from platforms like YouTube, an iframe provided by the service is used, which can also be made responsive with a little CSS.
Master multimedia on the web with: The video and audio tags, how to embed YouTube videos, and making them responsive.
2D Graphics with the <canvas> API
The <canvas> element provides a 2D drawing surface controlled by JavaScript. It is a blank slate where you can draw shapes, text, images, and create complex animations or manipulate graphics at the pixel level.
Basic Concepts
To draw on a canvas, you first need to get its "2D rendering context."
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Draw a line ctx.moveTo(0, 0); ctx.lineTo(100, 50); ctx.stroke(); // Draw a filled rectangle ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 150, 75);Image Manipulation
The true power of canvas lies in its ability to manipulate images. You can draw an image onto the canvas with drawImage(), and then get the data for each pixel with getImageData(). This allows you to apply custom filters and effects.
getImageData() returns a flattened array of RGBA values (Red, Green, Blue, Alpha) for each pixel. By iterating over this array, you can, for example, convert an image to grayscale:
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = imageData.data; for (let i = 0; i < data.length; i += 4) { const avg = (data[i] + data[i+1] + data[i+2]) / 3; data[i] = avg; // Red data[i + 1] = avg; // Green data[i + 2] = avg; // Blue } ctx.putImageData(imageData, 0, 0);Similarly, you can separate RGB channels, adjust contrast, or crop sections of an image using the variants of the drawImage() method.
Dive into the world of canvas with our guides: Basic Canvas Usage
Scalable Vector Graphics (SVG)
Unlike canvas, which is a bitmap, SVG (Scalable Vector Graphics) is an XML-based format for describing vector graphics. This means SVG graphics can be scaled to any size without losing quality, making them perfect for logos, icons, and adaptive graphics.
You can write SVG directly into your HTML using the <svg> tag.
Drawing SVG Primitives
SVG provides tags for drawing basic shapes:
<rect>: Rectangles and squares.<circle>: Circles.<ellipse>: Ellipses.<line>: Lines.<polygon>: Closed shapes with straight sides.<path>: Complex shapes defined by drawing commands.
<svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> Reuse with <defs> and <symbol>
For complex graphics, you can define shapes or groups of shapes within a <defs> or <symbol> tag. These elements are not rendered directly but can be reused in multiple places with the <use> tag.
This is extremely useful for creating libraries of icons or complex graphic components, as we demonstrated by building the Android logo with SVG.
Become an expert in SVG in HTML.
Section 4: Interactivity and Modern APIs
HTML5 goes far beyond static markup. It introduces a set of attributes and APIs that, in conjunction with JavaScript, allow for the creation of dynamic and interactive user interfaces, many of which previously required external libraries or complex hacks.
Native Drag and Drop
The HTML5 Drag and Drop API allows users to drag elements and drop them onto a designated area. It is an intuitive way to interact with the application, ideal for uploading files, reordering lists, or moving elements in an interface.
The process involves several key events:
- For the draggable element (
draggable="true"):ondragstart: Fires when dragging begins. Hereevent.dataTransfer.setData()is used to specify what data is being dragged.ondrag: Fires continuously while the element is being dragged.ondragend: Fires when dragging ends.
- For the target area (the "dropzone"):
ondragenter: Fires when a dragged element enters the zone.ondragover: Fires continuously while an element is over the zone. It is crucial to callevent.preventDefault()here to allow thedropto occur.ondragleave: Fires when the dragged element leaves the zone.ondrop: Fires when the element is dropped onto the zone. Hereevent.dataTransfer.getData()is used to retrieve the data.
This API is the foundation for functionalities like the "drag and drop" file upload seen in applications like Gmail.
Master this powerful API with our exhaustive guide: Drag and Drop in HTML5 (JavaScript).
Editable Content with contenteditable
The global contenteditable attribute allows the content of any HTML element (a div, a p, a span, etc.) to be edited by the user directly in the browser.
<div contenteditable="true"> <h3>This is an editable title</h3> <p>And this is a paragraph you can also edit. Try it!</p> </div> This simple attribute is the basis of many rich text (WYSIWYG) editors found on the web. By combining it with JavaScript to capture input events and apply formats, very powerful editing experiences can be created.
Find out how to use it in: Editable sections in HTML with the contenteditable attribute.
Native UI without JavaScript: <details> and <dialog>
HTML5 introduced elements that provide common UI behaviors without the need for JavaScript.
<details> and <summary>: Native Accordions
The <details> element creates an "accordion" or "disclosure" widget that the user can open and close to show additional content. The <summary> element provides the visible heading for the widget.
<details> <summary>Click to see more details</summary> <p>This is the hidden content that appears when clicked.</p> </details> It is an incredibly simple and accessible way to create FAQ sections or any collapsible content.
Learn more in: The details and summary tags.
<dialog>: Native Modal Windows
The <dialog> element represents a dialogue window or modal. It can be shown and hidden using JavaScript methods, but the browser handles the overlay behavior and focus trapping.
<dialog id="miModal"> <h2>Modal Window</h2> <p>This is a native dialog.</p> <button id="cerrarModal">Close</button> </dialog> <button id="abrirModal">Open Modal</button> const modal = document.getElementById('miModal'); document.getElementById('abrirModal').onclick = () => modal.showModal(); document.getElementById('cerrarModal').onclick = () => modal.close();The showModal() method opens the dialog as a modal, superimposing it over everything else and preventing interaction with the rest of the page.
Create your own native modals with: The dialog element in HTML5.
Meters and Progress Bars: <meter> and <progress>
HTML5 provides two semantic elements for visualizing numerical data in a range.
<progress>: Represents the progress of a task. It can be "determined" (if the progress is known, e.g.,value="70" max="100") or "indeterminate" (if the task is ongoing but it is unknown how much remains).<meter>: Represents a scalar measurement within a known range (such as disk usage or password strength). It has attributes likelow,high, andoptimumthat allow the browser to style the bar according to whether the value is good, fair, or bad.
<label for="descarga">Download Progress:</label> <progress id="descarga" value="35" max="100"> 35% </progress> <label for="disco">Disk Usage:</label> <meter id="disco" min="0" max="100" low="30" high="75" optimum="10" value="80">80/100</meter> Use these elements for a more semantic data visualization in: The Progress Bar element and The meter element.
Conclusion: HTML5 as an Application Platform
We have journeyed from the most fundamental HTML tags to the most complex and powerful APIs that the modern standard offers us. This journey demonstrates that HTML5 has transcended its original purpose of being a simple markup language. Today, it is a complete and mature application platform, capable of handling co