True Center Vertical and Horizontal CSS Div

Jess McKenzie picture Jess McKenzie · Jan 7, 2013 · Viewed 28.7k times · Source

How is it possible to create a true center CSS div cross browser for example to use within a holding page?

I have tried this 2007 css trick - How To Center an Object Exactly In The Center but as you can see from my JSFiddle of the code its not 100% center.

HTML:

<div class="center">
  <p>Text</p>
</div>

CSS:

.center{
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
  border:5px solid black;
}

Answer

icktoofay picture icktoofay · Jan 7, 2013

That technique requires the element to have a fixed width and height. You are not setting the width and height. Based on your border and margins, to center it, the width would need to be 190 pixels and the height would need to be 90 pixels. Using line-height and text-align in combination with a fixed width and height makes the text and border centered. Try it.

CSS

.center{
  position: fixed;
  top: 50%;
  left: 50%;
  width: 190px;
  height: 90px;
  line-height: 90px;
  text-align: center;
  margin-top: -50px;
  margin-left: -100px;
  border:5px solid black;
}