Using Flexbox for modal dialogs

10th June 2015 :: Website Design

How to make responsive modal dialogs. This is an article for web designers making easy modal dialogs. Using mainly CSS and jQuery.

The Struggle

To save development time, you normally use a plugin library (for example jQuery UI) for your modals. These libraries are often bloated for the regular use case and if you attempt to override the CSS manually it can be very tedious process. Let’s be honest, no-one likes the “!important” tag!

Another struggle if you choose not to use a plugin library and go down the path of doing it yourself, is positioning of the dialogs. JavaScript needs to determine the width and height of content, then position it absolutely from the top left.

As an example:
Let’s say you calculate the content height to be 200px.

.div {
     position: absolute;
     top: 50%;
     margin-top: -100px; //100px because it’s half of 200px

Then you would need to replicate this again with the width. You would need to recalculate the content if it dynamically changed, and factor in the window height so the dialog isn’t too high by setting maximum heights.

The Solution

The solution I am trialling is positioning via CSS3 flexbox. Firstly, you set a container outside of the main content:


<div class=’outer-flex-container’>
     <div class=’inner-flex-container’>
          CONTENT HERE

Then, the magic with display flex:


.outer-flex-container {
display: flex;
     align-items: center;
     justify-content: center;
     align-content: center;
     position: fixed;
     top: 0; left: 0;
     background: rgba(0,0,0,0.5);
.inner-flex-container {
     max-height: 80%;
     max-width: 80%;
     overflow-x: scroll;

* You will want to add the –webkit, -moz prefixes (or define a LESS or SCSS mixin).


Eliminates all manual calculations in regards to positioning the modal. No matter the content inside, the position of the modal will be perfectly centered, all determined by CSS and your browser.

You will want to hide and show based on click events with JavaScript, but that can be done very easily. If you‘re not sure where to start with that, have a look into jQuery on how to show() and hide() on html elements.


– Very basic understanding of jQuery needed.
– Heavy use of modern CSS to style custom dialog (eliminating the need for JS)
– No need for external JavaScript libraries
– Every modern browser will run it


– MS Internet Explorer 10+ (but is that really a con?)

Drop us a line

02 8004 8420


Level 1/102 Keira St,
Wollongong NSW 2500

Level 1/312 Peel St,
Tamworth NSW 2340

107 Faulkner St,
Armidale NSW 2350

Level 5/104 Commonwealth St,
Surry Hills NSW 2010