Create a Popup Overlay with CSS

Adding a popup to a website is a very common requirement when we design a website. In addition, some additional requests may include:

  • The popup should be centered both horizontally and vertically.
  • Using a fly-in effect.
  • It should overlay the existing HTML page and all elements.
  • Hide the if click detected anywhere outside of it.

In this post, we will follow a step-by-step walk-through to design a popup and meet the requirements above.

First, let’s start from placing a simple div that will center both horizontally and vertically.

Adding a div with id=popup in the body of the HTML code. Feel free to add some content in the div, of course.

Center the popup both horizontally and vertically

Using the CSS style below, we are first trying to center the popup.

Now take a look at the box model of the div, just to make sure the div is centered.

css box model

 

 

You can adjust the width and height for your div based on the content in your pop up. background-color property is set for purpose of testing.

 

Add a fly-in effect on the popup

Next, we can work on a fly-in effect by designing a fly-in class.

Add a Shadow Overlay

Sometimes you need your entire browser window with a black overlay in the background. So the popup in the front can draw more attention to the visitors.

We already added a fly-in class to the div to implement the fly-in effect. Now let’s create another class to do the show overlay.

Hide the popup when the user clicks outside of it

You may put a ‘Close’ or ‘X’ button in your popup, which is pretty straightforward.  So visitor can close it if they think it is disturbing.

In addition, to be more user-friendly, we want the popup to disappear from the screen when someone clicks anywhere outside the popup div. This is where javascript kicks in.

Put the javascript code below in the $( document ).ready()  function.

Basically, it adds an event handler for mouseup event on the HTML page. and if what is being clicked is not the popup div or any descendant element of it, then hide the it.