About

Labels

slider

Recent

Navigation

Center the element with absolute or fixed position


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.
#foo{
width:400px;
height:400px;
position:absolute; // Could be fixed
left:50%;
top:50%;
margin-left:-200px;
margin-top:-200px;
}

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.

Javascript

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

jQuery 

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

Demo 

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

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: