You should use CSS first, if you can. But if not, well, there's this.
Last active
August 29, 2015 14:20
-
-
Save cobbman/a24a96c02b7a67312daa to your computer and use it in GitHub Desktop.
Auto-center elements with jQuery
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
<div class="container"> | |
<div class="box-1 js-center">This will be in the center</div> | |
<div class="box-2">This will just be on the left</div> | |
</div> |
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
$('.js-center').each(function() { | |
var containerWidth = $(this).parent().width(); // not including padding | |
var elementWidth = $(this).outerWidth(); // including padding | |
var marginLeftValue = containerWidth / 2 - elementWidth / 2; | |
$(this).css('margin-left', marginLeftValue); | |
}); |
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
.container { | |
width: 960px; | |
padding: 25px; | |
border: 1px solid #ddd; | |
} | |
.box-1, | |
.box-2{ | |
width: 100px; | |
height: 100px; | |
} | |
.box-1 { | |
background: red; | |
} | |
.box-2 { | |
background: green; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment