Skip to content

Instantly share code, notes, and snippets.

@cobbman
Last active August 29, 2015 14:20
Show Gist options
  • Save cobbman/a24a96c02b7a67312daa to your computer and use it in GitHub Desktop.
Save cobbman/a24a96c02b7a67312daa to your computer and use it in GitHub Desktop.
Auto-center elements with jQuery

Auto-center elements with jQuery

You should use CSS first, if you can. But if not, well, there's this.

A Pen by William on CodePen.

License.

<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>
$('.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);
});
.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