search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
What a modal window actually is in HTML
Basic HTML structure for accessibility and control
CSS needed to make it look and behave like a modal
JavaScript to toggle and trap focus (minimal but necessary)
Home Web Front-end HTML Tutorial How to create a modal window with HTML and CSS? (UI Design)

How to create a modal window with HTML and CSS? (UI Design)

Jan 07, 2026 am 04:28 AM

A modal window is essentially an ordinary

implemented through CSS and JavaScript, not a special HTML element; it uses z-index layering, backdrop masks and aria attributes (such as aria-hidden, role="dialog") to achieve accessible interaction blocking effects.

How to create a modal window with HTML and CSS? (UI Design)

What a modal window actually is in HTML

A modal window isn't a special HTML element — it's just a <div> (or similar container) that's visually layered on top of the page, with interaction blocked behind it. Browsers don't enforce modality; you create it using CSS positioning, stacking context ( <code>z-index ), and focus/keyboard behavior.

Basic HTML structure for accessibility and control

Start with a wrapper that's hidden by default, includes a backdrop and content area, and uses semantic attributes:

 <div id="my-modal" class="modal" aria-hidden="true" role="dialog" aria-labelledby="modal-title">
  <div class="modal-backdrop"></div>
  <div class="modal-content" role="document">
    <h2 id="modal-title">Confirmation</h2>
    <p> Are you sure you want to delete this item?</p>
    <button id="confirm-btn"> Yes</button>
    <button id="cancel-btn"> No </button>
  </div>
</div>
  • aria-hidden="true" hides the modal from screen readers until opened
  • role="dialog" tells assistive tech it's a modal interaction
  • aria-labelledby links to the visible heading for context
  • Always include both backdrop and content as separate elements — makes styling and click-outside logic cleaner

CSS needed to make it look and behave like a modal

The key is combining position: fixed , proper z-index , and transitions — plus blocking background interaction:

 .modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
}
<p>.modal[aria-hidden="false"] {
opacity: 1;
pointer-events: all;
}</p><p> .modal-backdrop {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}</p><p> .modal-content {
background: white;
padding: 1.5rem;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
max-width: 90%;
max-height: 80vh;
overflow-y: auto;
position: relative;
z-index: 1001;
}</p>
  • Don't forget pointer-events: none on the outer .modal when closed — prevents accidental clicks through invisible layers
  • z-index must be higher than everything else (eg, navbars, headers), but the backdrop and content need different values ​​so content sits above backdrop
  • Use max-height overflow-y: auto on .modal-content — modals with long text will otherwise overflow the viewport
  • Avoid display: none for hiding — it breaks focus management and transitions

JavaScript to toggle and trap focus (minimal but necessary)

Without JS, the modal stays static. You need at minimum: open/close toggling and basic keyboard navigation:

 const modal = document.getElementById('my-modal');
const openBtn = document.getElementById('open-btn');
const closeBtns = document.querySelectorAll('#confirm-btn, #cancel-btn, .modal-backdrop');
<p>function openModal() {
modal.setAttribute('aria-hidden', 'false');
modal.querySelector('.modal-content').focus();
}</p><p> function closeModal() {
modal.setAttribute('aria-hidden', 'true');
openBtn.focus();
}</p><p> openBtn.addEventListener('click', openModal);
closeBtns.forEach(btn =&gt; btn.addEventListener('click', closeModal));</p><p> // Trap tab focus inside modal when open
modal.addEventListener('keydown', (e) =&gt; {
if (e.key !== 'Tab') return;
const focusable = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const first = focusable[0];
const last = focusable[focusable.length - 1];</p><p> if (e.shiftKey &amp;&amp; document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey &amp;&amp; document.activeElement === last) {
e.preventDefault();
first.focus();
}
});</p>
  • Setting aria-hidden="false" triggers the CSS transition — no need for extra classes
  • Always move focus into the modal on open ( .focus() on first focusable or content wrapper)
  • Focus trapping is non-negotiable for WCAG — users shouldn't tab out into background content
  • Don't rely only on clicking the backdrop to close — add Escape key support too (just add if (e.key === 'Escape') closeModal(); in the keydown handler)

The hardest part isn't showing the box — it's keeping focus locked, managing screen reader announcements, and handling resize or dynamic content without breaking layout. Most real-world bugs come from forgetting aria-hidden sync or skipping focus trapping.

The above is the detailed content of How to create a modal window with HTML and CSS? (UI Design). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to correctly migrate jQuery's drag and drop events to native JavaScript How to correctly migrate jQuery's drag and drop events to native JavaScript Mar 06, 2026 pm 05:15 PM

This article explains in detail the key pitfalls when migrating jQuery drag-and-drop logic (such as dragover/dragleave) to Vanilla JS - especially the problem of misuse of e.originalEvent causing dataTransfer failure, and provides directly runnable fixes and best practices.

How to make the images in a div fill with no margins while retaining the inner margins of the text How to make the images in a div fill with no margins while retaining the inner margins of the text Mar 07, 2026 pm 10:54 PM

This article explains how to keep the overall padding of the container so that the internal images are displayed close to the edge of the container, while the text content still maintains normal padding - the core is to separate the style scope and achieve precise layout through positioning and box model control.

Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Mar 09, 2026 pm 08:15 PM

When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.

Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Mar 12, 2026 pm 08:51 PM

This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.

A complete guide to using the keyboard to control the smooth movement of HTML elements A complete guide to using the keyboard to control the smooth movement of HTML elements Mar 13, 2026 pm 10:18 PM

This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.

How to properly override default styles and implement custom CSS layouts in Divi theme builder How to properly override default styles and implement custom CSS layouts in Divi theme builder Mar 14, 2026 am 12:00 AM

This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.

How to dynamically pass HTML form data to analytics.track() method How to dynamically pass HTML form data to analytics.track() method Mar 13, 2026 pm 10:57 PM

This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.

How to optimize Lighthouse image scoring while maintaining high image quality How to optimize Lighthouse image scoring while maintaining high image quality Mar 11, 2026 pm 09:39 PM

This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.

Related articles