Tokyo, Japan |

========================================================================================================================================================================================================================

Show a popup in center of screen with dimmed background in HTML & CSS

Recently I was working on a HTML project where I had to show a popup window in the center of the screen, overlaying the page with a dimmed background. The popup itself had to be resizable proportionally and work in browsers on mobile devices (iOS, Android) and desktops.

I’ll reproduce a bare-bones solution here so you can implement in your own project. See a demo here.

First, for the dimmed background, create a 2×2 px image. Fill it with black and set its opacity to 70%. Save it as a PNG with transparency and name it OverlayBgr.png.

In your HTML, add the code for the popup with overlay:

<div id="overlay">
    <div class="popup">
    	I am a popup.
	</div>
</div>

This will create a container div for the dark background overlay with a popup inside.

In CSS, add this:

#overlay {
	position: fixed;
	background: url("OverlayBgr.png");
	background-repeat: repeat;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 10000;
}

#overlay .popup {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	margin: auto;
	width: 50%;
	height: 50%;
	background-color: white;
}

The above CSS sets OverlayBgr.png as the background image for the overlay div and repeats its so it fills the whole page. The z-index property is important — it makes the whole div the topmost layer so it covers the rest of the page. I set z-index to 10000 but the number doesn’t matter as long as it’s higher than any other z-index you’re using. Since it’s covering the page, this will also prevent clicks (or taps) on the content that’s in the background which is probably what you want.

In #overlay .popup I set width and height to percentage values so that the popup resizes proportionally according to the size of the screen.

Comments