LoginSignup
4
1

CSSで3Dのボックスを作る手順

Last updated at Posted at 2023-08-23

See the Pen Just reviewing how 3d works in css by FrontendKanazawa (@jikkensya) on CodePen.

CSSの3D表現の仕方をよく忘れるのですぐに思い出せるようにキューブを作る手順をまとめます。

1. HTML

  • 描画する範囲 : #scene
  • 横面 : .face.side
  • 上下の面 : .face.top, .face.bottom
<div id="scene">
  <div class="cube">
    <div class="face side">1</div>
    <div class="face side">2</div>
    <div class="face side">3</div>
    <div class="face side">4</div>
    <div class="face top">5</div>
    <div class="face bottom">6</div>
  </div>
</div>

2.CSSのベース

$cube_width:70vh;
#scene{
  perspective:$cube_width;
  width:$cube_width; height:$cube_width;
}
.cube{
  width:100%; height:100%;
  position:relative;
  transform-style:preserve-3d;
  transform:translateZ($cube_width / 2 * -1);
}
.face{
  position:absolute;
  width:$cube_width; height:$cube_width;
}

ポイント

  1. #sceneにperspectiveを設定する。codepenのサンプルで値を変更してみると分かりやすいと思います。
  2. .cubeのwidth,heightを100%にしてpositionをreleativeにする。.faceのpositionをabsoluteにする。
  3. .cubeをtranslateZで後ろに下げる。
  4. .cubeのtransform-styleをpreserve-3dにすることで.cubeをtransformした際に小要素の.faceにも影響を与えることが出来ます。
    codepenのサンプルでは.cubeをjavascriptで回転させていますが、.cubeのpreserve-3dを消すと正常に動作しなくなります。

3.CSSで面の移動

//横面
.side:nth-of-type(1){
  transform:
    translateZ($cube_width / 2);
}
.side:nth-of-type(2){
  transform: 
    rotateY(90deg) 
    translateZ($cube_width/2);
}
.side:nth-of-type(3){
  transform: 
    rotateY(180deg) 
    translateZ($cube_width/2);
}
.side:nth-of-type(4){
  transform: 
    rotateY(-90deg) 
    translateZ($cube_width/2);
}

//上下
.top{
  transform:
    rotateX(-90deg)
    translateZ($cube_width/2 * -1);
}
.bottom{
  transform:
    rotateX(90deg)
    translateZ($cube_width/2 * -1);
}

ポイント

transformでrotateした後にtranslateZを使います。上下の面でtranslateZをしているのに上下に動くのが変な感じがしますが、初めのrotateXでz軸が回転した後であることを認識すると納得できます。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1