In CSS, there are a few different ways that you can center HTML elements. If you’re working with block-level elements, you can use the margin: 0 auto trick, which uses margins to place any block-level element in the exact center of their parent element. That trick looks like this:
div{ margin: 0 auto; }
If you’re centering text, then you’ll probably use the simple and straightforward text-align property, like this:
p{ text-align: center; }
For elements that aren’t block-level or text (typically, text tags are block-level elements unless they’ve been assigned a different display property), it’s a little bit more tricky to center them. A good hack for this situation is to set the positioning to absolute or relative, and then give the left property a value of 50%.
.inline-div{ position: absolute; left: 50%; }
If none of these tried and true CSS methods are working for you, there’s also a way that you can center just about any element to the middle of a page using only jQuery code. The following snippet shows you how to create a function that you can add to your scripts that should be able to center anything:
jQuery.fn.centerElement = function () { this.css ("position", "absolute"); this.css ("top", ($ (window). height () - this.height ()) / 2 + $ (window). scrollTop () + "px"); this.css ("left", ($ (window). width () - this.width ()) / 2 + $ (window). scrollLeft () + "px") return this; }
The code above actually works by manipulating the CSS properties of the element that you choose to pass through your function. First we add position: absolute to the element. Then we add a value to the top property that we calculate using an equation (we subtract the height of the element from the height of the window, then divide that by the vertical position of the scrollbar, plus 2, plus px, so that our answer is in pixels). For the left property, we use almost the exact same equation to find the number that should be the property’s value, except we find the horizontal position of the scrollbar, rather than the vertical. So basically, this jQuery code acts in a very similar way to the hack above (the one where we used the element’s positioning and left value to horizontally center it).
The difference between the jQuery code and the CSS code is that it centers the element both horizontally and vertically. Additionally, the numbers in the top and left properties are calculated very precisely. To use this function, you’ll just need to choose the element (or elements) that you’d like to center and then pass it through your new function, like this:
$('.center-me').centerElement();
That’s all it takes to use jQuery to center your element on a page. Using jQuery to center elements shouldn’t be your first instinct, because it is slower than using CSS. But if you find yourself in a situation where for whatever reason CSS isn’t working, or you’d like to be able to dynamically center your elements, this is a good option for you.