29

I often use this code to center a div in view:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

It works great on Firefox, Internet Explorer and Chrome, however not in Safari.

What's a workaround to center an image in Safari web browser?

NineCattoRules
  • 2,253
  • 6
  • 39
  • 84

4 Answers4

36

You need another vendor prefixed style.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Please refer below to know which browser supports what and what prefix has to be added. http://caniuse.com/#feat=transforms2d

Muthukannan Kanniappan
  • 2,080
  • 1
  • 16
  • 18
  • 9
    The answer is good, but would be perfect with one modification: *Prefixed versions should come before the unprefixed version*. In other words, put the W3C standard property after the vendor-prefixed properties. Here's why this is important: http://stackoverflow.com/q/7080605/3597276 – Michael Benjamin Jan 04 '16 at 00:19
17

Here is what works for me on all tested browsers and mobile devices (Chrome, IE, Firefox, Safari, iPad, iphone 5 and 6, Android).

The key for safari (including ios devices) is to add the other transform css rules and not just:

transform: translateY(-50%);

You need to add to it this group of rules:

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

Here is some working code of mine:

img.ui-li-thumb {
    position: absolute;
    left: 1px;
    top: 50%;

    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}
Murf
  • 487
  • 5
  • 9
  • 5
    Oh this is just beautiful. It's not enough to have ´-webkit-transform: translateY(-50%);´ but you need to have the other vendors as well for. Well done Apple, super design work there. Take a bow. – rory Nov 17 '16 at 13:18
  • 1
    @rory These different prefixes are to support certain versions of internet explorer (-ms), firefox (-moz), and opera (-o). The -webkit prefix is for webkit browsers (chrome and safari). So it's definitely not just an Apple thing. It's a standards thing. – Adam Fraser Mar 01 '18 at 14:35
1

In some cases you'll have to use:

-webkit-transform: translate3d(-50%,-50%,0);

Sometimes works better with mobile browser.

Iggy
  • 2,014
  • 25
  • 21
1
.some-element {
  transform: translate(50px 50px) rotate(15deg) scale(1.2);
}

if the above transform doesn't work for you, you can write those out individually as their own properties:

.some-element {
  translate: 50px 50px;
  rotate: 15deg;
  scale: 1.2;
}

reference: https://css-tricks.com/css-individual-transform-properties-in-safari-technology-preview/

Elias
  • 21
  • 3