jQuery: centering an element within the viewport

Centering an element within the viewport is one of the most required tasks during a front-end development process. In this post I'm going to show you how to accomplish this task with jQuery by using a common CSS approach. In fact, in CSS there's a simple method to center an element within the viewport: first, you set the top and left properties to 50% and then you use negative values for the top and left margin which must be equal to the half of the element's height and width, respectively. This CSS approach works fine when your element has both width and height set, but there are many cases when this computation cannot be done. And in these cases you can use jQuery, like so:

$(document).ready(function() {

    var elementWidth = $('#branding').outerWidth();
    var elementHeight = $('#branding').outerHeight();

    var offsetTop = Math.floor(elementHeight / 2);

    if(offsetTop % 2 !== 0) {
        offsetTop += 1;


    var offsetLeft = Math.floor(elementWidth / 2);

    if(offsetLeft % 2 !== 0) {
       offsetLeft += 1;


      top: '50%',
      left: '50%',
      marginLeft: - offsetLeft,
      marginTop: - offsetTop


First, we get the dimensions of the element by using outerWidth() and outerHeight(). This allows us also to include padding and border.Then we get the top and left offset by dividing the previous dimensions by two and rounding them to the nearest even number, if possible. Finally, we use the CSS solution discussed earlier inside the css() method. You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.