A Modal Cure in Pure CSS – No Wrappers, no JavaScript, no BS

Modals. They’ve been the subject of countless hacks over the years (I did a cross-browser one a while ago here), but due to cross-browser considerations, they usually are less than elegant in their implementation.

Well, if you don’t care about IE < 9, things are about to get much, much easier. This little trick is so simple it’s going to make you cry, in fact it’s so easy, it may cause you to audibly curse IE louder and more passionately than you ever have:

<div id="modal">
    <!-- YOUR CONTENT HERE (seriously, it's just one div) -->
</div>
#modal {
    display: block;
    position: fixed;
    top: 50%;
    left: 50%;
    box-sizing: border-box;
    transform: translate(-50%, -50%);
}

Here’s a fiddle so you can see it in action:

Yeah I know, all those hours wasted on wrapper divs, tables, crazy CSS, and performance-robbing JS, all to get hoodwinked by some top/left positioning and a transform property, go figure.

6 comments
Fabio Miranda Costa
Fabio Miranda Costa

Oh yeah right, didn't notice, from the code, that it was responsive. Thanks 

Louis-Rémi Babé
Louis-Rémi Babé

Yep, this `transform: translate(-50%);` is very useful in many situations and makes me hate IE8 every time. I like the previous dialog you created as well. The ugly markup is not really a problem, as it's usually generated by a library.