sreesreenu
sreesreenu

Reputation: 1057

CSS 3 rotateY() and rotateX() not working as expected

I am trying out the new features in css3 while i found that rotateY() and rotateX() is not giving expected results. I have a single div in the page

<div id="element"></div>

This is the css

#element{
    position: relative;
    margin: 0 auto;
    width: 200px;
    height: 200px;
    top: 300px;
    background-color: yellow;
    transform: rotateY(45deg);
}

This is the expected result

This is what i get

The blue shape is what i want and yellow is what i get

Upvotes: 2

Views: 6513

Answers (2)

Weafs.py
Weafs.py

Reputation: 23002

You need to add a container and give it perspevtive: 500px to get a 3D looking effect.

#container {
  -webkit-perspective: 500px;
  perspective: 500px;
}
#element {
  position: relative;
  margin: 0 auto;
  width: 200px;
  height: 200px;
  top: 10px;
  background-color: yellow;
  -webkit-transform: rotateY(45deg);
  transform: rotateY(45deg);
}
<div id="container">
  <div id="element"></div>
</div>

Upvotes: 4

Passerby
Passerby

Reputation: 10080

You may want to complete your transform and perspective style rule:

jsfiddle demo

body{
    -webkit-perspective:200px;
    -moz-perspective:200px;
    perspective:200px;
    -webkit-perspective-origin:center 400px /* 300px + 200px/2 */;
    -moz-perspective-origin:center 400px /* 300px + 200px/2 */;
    perspective-origin:center 400px /* 300px + 200px/2 */;
    -webkit-transform-style:preserve-3d;
    -moz-transform-style:preserve-3d;
    transform-style:preserve-3d;
}
#element{
    position: relative;
    margin: 0 auto;
    width: 200px;
    height: 200px;
    top: 300px;
    background-color: yellow;
    -webkit-transform: rotateY(45deg);
    -moz-transform: rotateY(45deg);
    transform: rotateY(45deg);
    -webkit-transform-origin:center;
    -moz-transform-origin:center;
    transform-origin:center;
}
<div id="element"></div>

The parent of #element (not necessary <body>) has to have:

  • perspective so your browser knows how "far" the viewport is from #element, and render the rotation effect accordingly;
  • perspective-origin so your browser knows where the "center" of your viewport is;

The transform-style:preserve-3d do not seem to be necessary in this specific case, and IE doesn't support this feature yet. I just added it out of habit.

Upvotes: 3

Related Questions