0

I know there are few way to positon a div center vertically and horizontal using css. But for old phone support, I have to do it with js.

http://jsfiddle.net/ncsy9khf/1/

div{
    width:50px;
    height:50px;
    background:orange;
    position:relative;
    margin: 0 auto;
    display:block;
}

How do I do the calculation to know what value of my margin top to make the box center center?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
Jamie Anderson
  • 1,453
  • 3
  • 13
  • 13

2 Answers2

2

This is my favorite way:

position:relative;
top: 50%;
transform: translateY(-50%);
left: 50%;
transform: translateX(-50%);

This 5 lines can vertically and horizontally almost anything

Fiddle


I learned this method from this article

Support tables here

You can expect 95% of your users have this work perfectly


More browser friendly way:
position:relative;
top: 50%;

-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);

left: 50%;

-ms-transform: translateX(-50%);
-webkit-transform: translateX(-50%);    
transform: translateX(-50%);

Friendly Fiddle

Downgoat
  • 13,771
  • 5
  • 46
  • 69
1

Just use plain CSS:


.parent {
  position: relative;
  width: 160px;
  height: 160px;
  background: #eee;
}

.centered {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: #FF9800;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
<div class="parent">
  <div class="centered"></div>
</div>

The parent element must have position:relative; (In which you are planning to center the div)

Also there's no need to add display:block; to div elements - they are block elements by default

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167