Created
May 20, 2013 13:33
-
-
Save kentcdodds/5612254 to your computer and use it in GitHub Desktop.
This is to help remind me how to do some useful UI things like centering elements in the window as the window size changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var centerElement = function ($element) { | |
$element.css("position","absolute"); | |
$element.css("top", Math.max(0, (($(window).height() - $($element).outerHeight()) / 2) + $(window).scrollTop()) + "px"); | |
$element.css("left", Math.max(0, (($(window).width() - $($element).outerWidth()) / 2) + $(window).scrollLeft()) + "px"); | |
return $element; | |
} | |
/* | |
Invoke this like this: | |
$(window).resize(function() { | |
centerElement($('#container')); | |
}); | |
$(window).resize(); | |
*/ |
Thanks dude
@timehat, too explicit. I prefer kent's dynamic way if I were to go JS. If I were to go all CSS, I'd opt for using table-cell with vertical-align, assuming I could use a less compatible display type on an element.
<style>
html, body {height:100%; margin:0;}
</style>
<div style="display:table; width:100%; height:100%;">
<div style="display:table-cell; vertical-align:middle; text-align:center;">
Look at me, I'm fully centered!
</div>
</div>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Set width/height of outermost div (or position absolutely to fill the window, if desired), and let the browser do the work for you.