0

I'm trying to achieve centered vertical and horizontal alignment of a div. This is the styling I'm using:

.box{
  position:fixed;
  display:block;
  width:200px;
  height:400px;
  top:50%;
  left: 50%;
  width: 50%;
  transform: translateX(-50%) translateY(-50%);
  background:#ccc;
}

This style works perfectly in Firefox but not in Chrome. Here's the example: http://codepen.io/0leg/full/HJjrK

The interesting thing is that I lifted this styling from a modal window on this tutorial http://tympanus.net/Development/ModalWindowEffects/, and for some reason this works perfectly in webkit browsers...

2 Answers2

0

As you know the height and width of the div, I would change your CSS to this:

.box{
    position:absolute;
    width:50%;
    height:400px;
    top:50%;
    left: 50%;
    margin-top: -200px; /* Half the height of the div */
    margin-left: -25%; /* Half the width of the div */
    background:#ccc;
}

You're moving the div half way down and across the page, and then negatively margining it back by half of it's width.

http://jsfiddle.net/davidpauljunior/utPhs/2/

Note: You had two width declarations, I presumed you wanted the second one (50%), so removed the first one. I changed position fixed to absolute but it works with both, and I removed the display:block as <div> is already a block level element.

davidpauljunior
  • 8,238
  • 6
  • 30
  • 54
0

That is simply because in even the latest version of Chrome, you will need to use the vendor prefix -webkit- for CSS3 transforms. Mozilla Firefox has been supporting unprefixed transform since v16 (current v25), and ironically so is the current version of IE. More information on browser support is available here: http://caniuse.com/transforms2d

Therefore, use the vendor prefix (just -webkit- is sufficient, unless you want to support older versions of IE and Firefox, then use their respective vendor prefixes, too):

.test {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background: red;
    width: 200px;
    height: 200px;
}

http://codepen.io/terrymun/pen/zCgkI

Terry
  • 63,248
  • 15
  • 96
  • 118