Bottom Or Center Aligning Element using JavaScript and jQuery

Recently I had to bottom align an element on one of my website template, I knew there were many methods for doing it using CSS. But the CSS codes just won’t work for my template because of many reasons, but I was quickly able to figure out how I could do this using JavaScript. Below I am sharing how we can bottom align or center align an element using JavaScript and jQuery.

Including jQuery

First of all we will need to include the jQuery JavaScript Library since we will be using jQuery. At least jQuery Version 1.2 will be needed for the functioning of the below code(s). Though the .css() has been in jQuery since Version 1.0 but the position CSS property was included in jQuery Version 1.2.

{code type=HTML}

{/code}

I have included the compressed version of jQuery Version 1.2 library. However, I recommended to include the latest version of jQuery JavaScript Library. For the latest version, simply include this instead.

{code type=HTML}

{/code}

Function For Center Aligning the Element

Writing the function is not really difficult, here is the function below for Center Aligning:
{code type=HTML}

{/code}

Function For Bottom Aligning the Element

And for Bottom Aligning:
{code type=HTML}

{/code}

In the above code(s) FunctionName is your desired function name and #ElementName is the id of the element which you want to center or bottom align, you can even use this keyword here.

Calling Function

After writing the function, simply call it.

{code type=HTML}

{/code}

Demonstration

You can see a live demo for Center Aligning an element here.
And for Bottom Aligning an element here.

Note

Though this method works most of the time, but still if you see it not functioning properly or not perfectly center or bottom aligning the element, then manually add some numerical pixel values to the variables used above.

  • This seems like a lot of work for what you are trying to achieve. When you have to hack around with javascript and jQuery to get something like this you may want to take a look at your template and see how you can make it more flexible. This will totally mess up the formatting of page if javascript is disabled on the users browser although this is now very rare.