.cylinder { width: 100px; height: 100px; border-radius: 50%; border-top: 50px solid #f00; border-bottom: 50px solid #00f; position: relative; } .cylinder:before, .cylinder:after { content: ""; position: absolute; width: 100%; height: 50px; left: 0; } .cylinder:before { bottom: 0; background-color: #f00; transform-origin: bottom; transform: perspective(1000px) translateZ(-25px) rotateX(45deg); border-radius: 50%; } .cylinder:after { top: 0; background-color: #00f; transform-origin: top; transform: perspective(1000px) translateZ(-25px) rotateX(45deg); border-radius: 50%; }
上面的代码段可以创建一个CSS圆柱块。其中,width和height属性定义了圆柱的大小和形状,border-radius属性定义了圆柱的边缘为圆形,position:relative使得其位置相对于其他元素相对定位,而:before和:after伪元素则负责创建顶部和底部的半圆形部分,并利用transform属性实现3D效果。