利用CSS3简单实现一个3D立方体(两种方式)

写好html布局:

<div class="box">
	<div class="box1">1</div>
	<div class="box2">2</div>
	<div class="box3">3</div>
	<div class="box4">4</div>
	<div class="box5">5</div>
	<div class="box6">6</div>
</div>

第一种方式:
先旋转后位移(旋转基线不变)

css3代码:

		  * {
				margin: 0;
				padding: 0;
			}

			body {
				/* 3D模式 */
				transform-style: preserve-3d;
				perspective: 900px;
			}

			.box {
				width: 200px;
				height: 200px;
				margin: 300px auto;
				position: relative;
				/* 3D模式 */
				transform-style: preserve-3d;
			}

			.box div {
				width: 200px;
				height: 200px;
				font-size: 40px;
				font-weight: bold;
				line-height: 200px;
				text-align: center;
				color: red;
				position: absolute;
			}

			.box1 {
				background: rgba(255, 255, 255, 0.5);
				/*上*/
				transform: translateY(-100px) rotateX(90deg);
			}

			.box2 {
				background: rgba(255, 200, 100, 0.5);
				/*右*/
				transform: translateX(100px) rotateY(90deg);
			}

			.box3 {
				background: rgba(0, 20, 200, 0.5);
				/*下*/
				transform: translateY(100px) rotateX(-90deg);
			}

			.box4 {
				background: rgba(200, 255, 70, 0.5);
				/*后*/
				transform: translateZ(-100px) rotateY(180deg);
			}

			.box5 {
				background: rgba(255, 0, 255, 0.5);
				/*前*/
				transform: translateZ(100px);
			}

			.box6 {
				background: rgba(85, 255, 255, 0.5);
				/*左*/
				transform: translateX(-100px) rotateY(-90deg);
			}

第二种方式:
改变旋转基线再旋转

			* {
				margin: 0;
				padding: 0;
			}

			body {
				/*3D模式*/
				transform-style: preserve-3d;
				perspective: 900px;
			}

			.box {
				width: 200px;
				height: 200px;
				background: rgba(0, 0, 0, 0.5);
				margin: 300px auto;
				position: relative;
				/*3D模式*/
				transform-style: preserve-3d;
				/*旋转20度方便查看旋转变化*/
				transform: rotateX(-20deg);
			}

			.box div {
				width: 200px;
				height: 200px;
				font-size: 40px;
				color: #f00;
				line-height: 200px;
				text-align: center;
				position: absolute;
			}

			.box1 {
				background: rgba(0, 200, 100, 0.8);
				/*右面*/
				/*旋转基线*/
				transform-origin: right center;
				transform: rotateY(90deg);
			}

			.box2 {
				background: rgba(110, 200, 100, 0.8);
				/*上面*/
				/*旋转基线*/
				transform-origin: center top;
				transform: rotateX(90deg);
			}

			.box3 {
				background: rgba(200, 200, 100, 0.8);
				/*下面*/
				/*旋转基线*/
				transform-origin:  bottom center;
				transform: rotateX(-90deg);
			}

			.box4 {
				background: rgba(10, 200, 0, 0.8);
				/*前面*/
				transform: translateZ(200px);
				/*位移*/
			}

			.box5 {
				background: rgba(0, 20, 200, 0.8);
				/*左面*/
				/*旋转基线*/
				transform-origin: left center;
				transform: rotateY(-90deg);
			}

			.box6 {
				background: rgba(100, 200, 100, 0.8);
				transform: rotateY(180deg);
			}
发布了11 篇原创文章 · 获赞 0 · 访问量 109

猜你喜欢

转载自blog.csdn.net/qq_39347364/article/details/104959485