Centering an element using jQuery

After you have a good grasp on both HTML and CSS you can create some great websites, but what if you want your website to do more?  To really build websites which are dynamic on the front-end and powerful on the back-end I suggest branching out into both jQuery and PHP.  I’ll cover PHP at a later date, but I just wanted to touch on jQuery.

Once you start to dabble a little into jQuery you’ll instantly be able to appreciate what it can do for you with just a few lines of code.  While adding basic interactivity can be handled with the increased capabilities of CSS3, a lack of browser support (most notably from IE8 and below) make it tricky to rely on for elements which are key to user experience.  For anyone reading this who is contemplating learning jQuery, I just wanted to run through a) how to include the jQuery framework into your site, and b) a quick example to show you how to use jQuery to help solve a common web design problem.

Let’s get started…

Getting your site jQuery ready couldn’t really be easier.

Step 1) Include <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> into the <head> of your page.  This just includes jQuery’s script library in your page, so anytime you use a jQuery function it dips into this file and runs what it needs.  As an alternative to linking to the google hosted version as we are here, you can download the latest version from http://jquery.com/, and link to it in the same way.  The advantage to using the google hosted version is that if a user has visited another site which also used the google hosted version (which is pretty common), then it will already be in their cache and they won’t have to download your version (compressed: 31kb, uncompressed 229kb).

Step 2) Use $(document).ready(function(){ which will execute your jQuery code once the page is ready.  You’ll see an example of how to use this in the example following.  You can also just use $(function(){ as a shortcut replacement.  You can either include this into your webpage by encapsulating it in <script type="text/javascript"> </script> tags, or you can put it into an a separate JavaScript file and include that file in your <head> the same way that we included the jQuery library.

And that’s all there is to getting your page jQuery ready.  You can include other jQuery libraries or plugins into your page, such as the jQuery UI which enables a quick and easy addition of useful user-interface elements (drag and drop, sliders, tabs etc), or a whole range of free, open-source plugins created by other developers.

Let’s solve a problem…

Say you have an element (an image, div, video etc) and you want to center it horizontally and vertically within another element (a containing box for example).  How would you do this?  Well there are a few ways if you know the dimensions of the element you’re trying to center; you can set the padding of it’s container to center it perfectly in the middle, you can absolutely position it and set top and left values, you could even use display: table-cell; vertical-align: middle;.  However, those solutions are not very flexible, and apart from the latter they would only work if you know the dimensions of the element you’re trying to center.  But what if you don’t?  Or what if you have hundreds of elements of different sizes that each need centering within their own containers (products on an ecommerce site for example).  Using jQuery we can create a simple solution which will measure the dimensions of the element and then adjust the padding of its container accordingly to center it.

Let’s say we have the following HTML elements:

<div class="container">
<div class="box"></div>
</div>

And the following CSS to style it:

.container{
background: orange;
width: 500px;
height: 500px;
}
.container .box{
width: 100px;
height: 100px;
background: #333;
}

That gives us this:  http://johndoesdesign.com/dev/journal/jquery/intro/before.html

Now let’s add some jQuery to center that element:

$(function() {
//Find the height of the container and assign it to a variable:
var containerHeight = $('.container').height();
//Find the width of the container:
var containerWidth = $('.container').width();
//Calculate a value for the containers top padding:
var offsetTop = (containerHeight - $('.box').height())/2;
//Calculate a value for the containers left padding.
var offsetLeft = (containerWidth - $('.box').width())/2;

 

//Alter the CSS properties of the container with it's new padding and dimensions.
$('.container').css({'padding-top': offsetTop, 'padding-left': offsetLeft, 'height': containerHeight - offsetTop, 'width': containerWidth - offsetLeft});
});

Using the small amount of jQuery gives us this:  http://johndoesdesign.com/dev/journal/jquery/intro/after.html

To test the flexibility of our solution we can change the dimensions of both the container and the box elements to show that the jQuery will still center the object no matter what the sizes:  http://johndoesdesign.com/dev/journal/jquery/intro/after-2.html

We can then go a step further and tackle the problem of centering multiple elements, each within their own container.  This could be used to display images in a gallery, products on a ecommerce site, or in a variety of other situations.  We use the jQuery ‘each’ function to loop through all of the container elements on the page and apply the measurement and positioning calculations to each one:

$('.container').each(function(){
var containerHeight = $(this).height(),
containerWidth = $(this).width(),
offsetTop = (containerHeight - $(this).find('.box').height())/2,
offsetLeft = (containerWidth - $(this).find('.box').width())/2;

 

$(this).css({'padding-top': offsetTop, 'padding-left': offsetLeft, 'height': containerHeight - offsetTop, 'width': containerWidth - offsetLeft});
});

This is the result:  http://johndoesdesign.com/dev/journal/jquery/intro/after-3.html

This is just a very simple example of how jQuery can help to complete tasks which CSS alone cannot.

Any questions or comments, let me know!

One much appreciated response...

  1. Pingback: How to center a menu in WordPress

Feel free to add your comment..

Your email address will not be published.