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:
#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.
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.
Nice! or you can make a responsive one:
http://jsfiddle.net/fabiomcosta/tvBrs/
This should work on IE7+
This modal is already responsive: http://fiddle.jshell.net/HUZYN/9/show/ <– same demo as the embedded fiddle above, fluidly adapts based on container size…perhaps you define "responsive" differently?
Oh yeah right, didn’t notice, from the code, that it was responsive.
Thanks
I love it, but I’ve noticed some wackiness with forms: http://jsfiddle.net/HUZYN/9/
Any workarounds you can think of?
I meant http://jsfiddle.net/HUZYN/12/
I think this may be something to do with jsFiddle’s small iframe editor preview pane, if you open your example’s preview pane alone, it works just fine: http://fiddle.jshell.net/HUZYN/12/show/
Yeah, I just checked, in jsFiddle’s 4 pane view, the live preview iframe is actually extended below what you can visually see, giving the modal the appearance of being off center. If you use Firebug and fix it, you’ll see it is perfectly fine and not caused by the modal 😉
This is a browser bug, they are not shifting the paint of the chrome-level UI elements to match the translation of the input elements. I’ll file a bug for this.
Um, I don’t know that this is a modal. It’s a nice approach to a centered popup, but I can still interact with the background content, so the popup has no modality. http://jsfiddle.net/rwadkins/HUZYN/28/
I would not use this anymore. It’s far better to simply absolute position a modal element at 50% left and top and use CSS translate -50% to set it to center. This was created before those existed, and is now obsolete.
You can see here
http://jsfiddle.net/5w82n33j/
I would not use this anymore. It’s far better to simply absolute position a modal element at 50% left and top and use CSS translate -50% to settle center. This was created before those existed, and is now obsolete.