Using Flexbox for modal dialogs

How to make responsive modal dialogs. This is an article for web designers making easy modal dialogs. Using mainly CSS and minimal 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 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 <Link to jQuery> on how to show() and hide() on html elements.


– Very basic understanding of jQuery needed.
– Heavy use of CSS to style custom dialog (eliminating the need for JS)
– No need for external JavaScript libraries
– Every good browser will run it
– MS Internet Explorer 10+ (but is that really a con?)


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

you might also like
Your web browser is out-of-date. Update your browser for more security, comfort and the best experience on this site. Click here to update your browser.