Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created May 20, 2013 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentcdodds/5612254 to your computer and use it in GitHub Desktop.
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.
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();
*/
@timehat
Copy link

timehat commented Oct 2, 2013

<div style="text-align: center; height: 500px;">
  <div style="vertical-align: middle; height: 100%; width: 0; display: inline-block;"></div>
  <div style="display: inline-block; text-align: start;">
    Look, ma! No JS needed! :)
  </div>
</div>

Set width/height of outermost div (or position absolutely to fill the window, if desired), and let the browser do the work for you.

@kentcdodds
Copy link
Author

Thanks dude

@adamculpepper
Copy link

@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