Open In App

How to show JavaScript alert box in the middle of the screen?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To create an alert box that occurs in the middle of the browser window we use CSS to style the alert box and JavaScript to control its appearance. Techniques include adjusting the alert box’s position using CSS properties as well as JavaScript event handling to trigger the alert box’s display to enhance user experience by ensuring that important alerts are displayed and easily visible to users.

Approach

  • The HTML structure contains a heading, a paragraph, a button, and a hidden div for the alert box.
  • The CSS styles utilize Flexbox to center the content vertically and horizontally within the viewport.
  • The alert box div is initially hidden (display: none;) and positioned fixed in the center of the screen using top: 50% and left: 50%.
  • JavaScript adds an event listener to the “Show Alert” button, toggling the display of the alert box (display: block;) when clicked.
  • Clicking the “Close” button inside the alert box triggers an inline JavaScript function to hide the alert box (display: none;).

Example: The code below shows an alert box in the middle of the screen using CSS and JavaScript.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Centered Alert Box</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        #alert {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
        }

        .heading {
            color: green;
            font-size: 40px;
        }
    </style>
</head>

<body>
    <h1 class="heading">
      GeeksForGeeks
      </h1>
    <h4> alert box in the middle Using CSS with Custom HTML</h4>

    <button id="show-alert">Show Alert</button>

    <div id="alert">
        <p>This is a centered alert message!</p>
        <button onclick="document.getElementById('alert')
                                   .style.display = 'none'">
                      Close
          </button>
    </div>

    <script>
        
          // Add an event listener to the "Show Alert" button
        document.getElementById('show-alert')
                  .addEventListener('click', function () {
            document.getElementById('alert')
                      .style.display = 'block';
        });
    </script>

</body>

</html>

Output:

Untitled-design-(11)

Output


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads