Search code examples
csscross-browseralignment

Aligning div of unknown size across browsers


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...


Solution

  • 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