theeggman85 theeggman85 - 24 days ago 6
CSS Question

CSS3 - translateZ based on percentage of parent div?

I have a webpage with a largescale model that follows this example (code found here).

In the code, you'll see that the translateZ arguments are all either 25px or -25px, which is half the height of the menu item and is very important for the spinning to work correctly.

This is my version of the code, click the cube face to rotate it. I am trying to make the same code work, but with a percentage-width and percentage-height div instead of static. The translateZ values are staying static, so you can see that this makes the cube look weird depending on the window size. How can I update the translateZ values to half the cube width/height whenever the window resizes?

I tried doing it with JavaScript but got this. The cube does not move on click and slides in and out of resizing, but it will move if you click it once and then resize the window. Why is that?

Answer

I don't think that you can set translateZ based on the div size. You can, however, use another div to get that efect; and this div can of course be based on the div size of the parent.

The html would ne the following:

<div id="base">
    <div class="raiser">raiser
        <div class="face1">FACE UP
            <div class="face2">side</div></div></div>
</div>

THe idea is that on the base div, I set the raiser div at 90 deg, and with a width of 50% of the parent. This way, at the right of the raiser we will get the correct Z position.

The CSS is the following:

div {
    -webkit-transform-style: preserve-3d;
}

#base {
    margin-left: 10%;
    width: 40%;
    height: 50%;
    font-size: 40px;
    -webkit-transition: 10s;
    background-color: rgba(128, 128, 128, 0.21);
}

.rotated {
    -webkit-transform: rotateY(90deg);
}

.raiser {
    -webkit-transform: rotateY(85deg);
    -webkit-transform-origin-x: 0%;
    position: absolute;
    width: 50%;
}

.face1 {
    background-color: lightblue;
    -webkit-transform: rotateY(-90deg);
    -webkit-transform-origin-x: 0%;
    position: absolute;
    width: 200%;
    left: 100%;
    top: 0px;
}

.face2 {
    background-color: lightgreen;
    -webkit-transform: rotateY(-90deg);
    -webkit-transform-origin-x: 0%;
    left: 100%;
    position: absolute;
    top: 0px;
    width: 100%;
}

Demo for webkit

In the demo you will see that there is a checkbox "tilt". If you check this, all the layout will rotate in the X axis, so that you can see the spatial layout.

Also, the raiser has a text and is rotated 85deg instead of 90, so that it is easier to see what is happening. The final code would be with the angle set at 90, and without text.