jQuery Flex Vertical Center plugin

This jQuery plugin provides an easy way to vertically center an element in its parent. Even if the parents height changes after resizing the browser window, in a fluid or responsive layout for example.

I created it during the CSSoff competition because I had a container with a background that had background-size: 100% on it. I created another plugin (will be on Github soon) which kept the proportions of the container the same even if it changed width in the fluid and responsive layout. There was some dynamic content within the container which needed to be properly centered within the container so I created this plugin to do just that.


Simply include ‘jquery.flexverticalcenter.js’ (which you can download on Github) in your project (after loading jQuery) like this:

<script defer src="js/jquery.flexverticalcenter.js"> </script>

Then call the plugin on the element which needs to be vertically centered in it’s parent.

<script> $(document).ready(function() { $('#element-to-be-centered').flexVerticalCenter(); }); </script>

This will take the parents height, the elements own height and calculate the distance the element should have from the parents top to be vertically centered. This value is applied to the top margin of the element by default.


You can pass one parameter to the plugin, which is the css attribute that the value should be set on. The default is ‘margin-top’, but you can pass any attribute you would like. Most probably ‘padding-top’ or ‘top’.

<script> $(document).ready(function() { $('#element-to-be-centered').flexVerticalCenter('padding-top'); }); </script>


The initial code was more or less borrowed from the awesome FitText plugin. http://fittextjs.com/

6 Responses to jQuery Flex Vertical Center plugin

  1. CJ says:

    This is beautiful! Are things supposed to be centered immediately? or only after resizing the window? I can’t get things centered immediately, but once I start resizing the window it works beautifully!

  2. Glad you like it.

    Are you displaying any images in the element that needs to be centered? Might be that the image hasn’t loaded yet when the height is calculated. Now that I think of it I have some ideas for a fix.

  3. CJ says:

    Thanks for the speedy reply! Yes, I’m trying to center text on top of an image. The parent box is determined by the size of the image.

  4. CJ says:

    I know virtually nothing about jquery, but I found that switching the load function dealio to “$(window).load(function()” provided some sort of help, even if it is a little slow.

  5. @CJ: I fixed the issue and updated the repo at Github. Now, after an image is loaded within the element the height is recalculated and the repositioned accordingly.

  6. Khema says:

    This is a huge time safer especially when making a responsive design, Thanks a lot Paul.

Leave a Reply

Your email address will not be published. Required fields are marked *