Last active
December 17, 2015 12:19
-
-
Save chill117/5608492 to your computer and use it in GitHub Desktop.
Extend jQuery with the .center() method. Allows you to easily center element(s) within a container (or the viewport).
This file contains hidden or 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
/* | |
|---------------------------------------------------------------- | |
| Description | |
|---------------------------------------------------------------- | |
Extend jQuery with the .center() method. Allows you to easily | |
center element(s) within a container (or the viewport). | |
|---------------------------------------------------------------- | |
| Dependencies | |
|---------------------------------------------------------------- | |
jQuery | |
|---------------------------------------------------------------- | |
| Notes | |
|---------------------------------------------------------------- | |
- Center the element(s) within their container by setting the | |
element(s) to 'position: absolute' and their container to | |
'position: relative' | |
- You can also center the element(s) within the viewport with | |
'position: fixed' | |
|---------------------------------------------------------------- | |
| Example Usage | |
|---------------------------------------------------------------- | |
To center an element on both axes within the body tag: | |
$('#some-element').center(); | |
To center an element on just the X axis within the body tag: | |
$('#some-element').center('x'); | |
To center an element on just the X axis within its parent element: | |
var someElement = $('#some-element'); | |
var parentElement = someElement.parent(); | |
someElement.center('x', parentElement); | |
And, chaining works too! | |
$('#some-element').center('x').addClass('centered'); | |
*/ | |
$.fn.center = function(axes, container) { | |
// Default to the body. | |
container || (container = $('body')); | |
// Default to both axes. | |
axes || (axes = 'xy'); | |
for (var i = 0; i < this.length; i++) | |
{ | |
var element = this.eq(i); | |
if (axes.indexOf('x') !== -1) | |
{ | |
var containerWidth = container.width(); | |
var elementOuterWidth = element.outerWidth(true); | |
var left = (containerWidth - elementOuterWidth) / 2; | |
element.css('left', left); | |
} | |
if (axes.indexOf('y') !== -1) | |
{ | |
var containerHeight = container.height(); | |
var elementOuterHeight = element.outerHeight(true); | |
var top = (containerHeight - elementOuterHeight) / 2; | |
element.css('top', top); | |
} | |
} | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment