15 January 2016

Centre align lots of elements within their containers using jQuery

Following on from Centre align image within a fluid element using jQuery, here’s an extension of the same script applied to multiple elements on the same page.

So firstly you’ll need some HTML with a bunch of stuff that needs centring:

Get things moving in the right direction by absolute positioning things with CSS:

Now here’s our complete jQuery:

So, what are we doing?

Firstly we place our script in a reusable function. Not necessary, but it can help keep things tidy:

Then we target each instance of our target CSS class, in this case ‘.centreme’ within ‘.tile’ within ‘.container’:

Now we get the full height and width of each instance using jQuery’s outerWidth, outerHeight and this:

And now we take these values, divide them by two, and offset the top and left position of our targets accordingly:

In my example I’m wanting to centre align images, so to avoid miscalculations, I make sure to run my function after everything in the window has loaded:

View the working demo.