Blogger Ever

Center the element with absolute or fixed position

Since their is no specific property to put the element in centre while in absolute or fixed position, you can use a trick over here. You can use Javascript, jQuery or CSS for that.

The absolute or fixed elements have special properties applicable that are top, left, right and the bottom. These properties can have values in percentage but not any values to make the element flat in centre.

For that we are going to use margin-left property. We have two ways to get it.
Read More:

For fixed width and height

For fixed width element, set left to 50% while margin-left to negative and half of the width. While top to 50% and half of the height to negative margin-top.
position:absolute; // Could be fixed

For Fluid Elements

You can either use jQuery or Javascript, I'm going for both of them. Nothing new, just calculate height and width of the element, divide it by 2 and then add margins accordingly.


  var foo = document.getElementById('foo'),
      fooWidth = foo.offsetWidth / 2,
      fooHeight = foo.offsetHeight / 2; = "-" + fooWidth + 'px'; = "-" + fooHeight + 'px';
Note: offsetWidth includes width with padding and borders only excluding margins.


  var foo = $('#foo'),
      fooWidth = foo.outerWidth() / 2,
      fooHeight = foo.outerHeight() / 2;
      'margin-left': '-' + fooWidth + 'px',
      'margin-top': '-' + fooHeight + 'px'


See the Pen VYmKyo by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.