如何在CSS中旋转背景图片?六边形背景逐元素旋转问题
问题描述
我有一张六边形背景图片,希望旋转该六边形图片,使虚线移动到不同的侧边。
我尝试使用:nth-child伪类实现,但未生效。
以下是我的实现代码:
.node::before { content: ""; position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: -1; background-size: 120px 120px; background-image: url('https://i.ibb.co/4p1pQtF/Component-1.png'); } .node { position: relative; overflow: hidden; display: flex; z-index: 0; align-items: center; justify-content: center; height: 120px !important; width: 120px !important; margin-bottom: 10px; border: 1px black solid; } .node::nth-child(2) { transform: roate(60); } .node::nth-child(3) { transform: roate(120); } .node::nth-child(4) { transform: roate(180); } .node::nth-child(5) { transform: roate(240); }
<div class="node"> 1 </div> <div class="node"> 2 </div> <div class="node"> 3 </div> <div class="node"> 4 </div> <div class="node"> 5 </div>
我该如何为每个.node元素盒子中的六边形图片旋转60度?
更新内容
我还尝试了以下代码:
.node:nth-child(2)::before { transform: roate(60deg); } .node:nth-child(3)::before { transform: roate(120deg); } .node:nth-child(4)::before { transform: roate(160deg); } .node:nth-child(5)::before { transform: roate(180deg); }
解决方案
你的代码存在两个核心问题:
- 拼写错误:将
rotate误写为roate,导致CSS旋转属性完全失效。 - 角度设置不合理:六边形每条边对应60度旋转,应该依次递增60度(60/120/180/240),而非160这类非60倍数的角度。
修正后的完整代码如下,同时给伪元素显式声明旋转中心,确保背景图旋转时不偏移:
.node::before { content: ""; position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: -1; background-size: 120px 120px; background-image: url('https://i.ibb.co/4p1pQtF/Component-1.png'); transform-origin: center center; /* 固定旋转中心为元素中央 */ } .node { position: relative; overflow: hidden; display: flex; z-index: 0; align-items: center; justify-content: center; height: 120px !important; width: 120px !important; margin-bottom: 10px; border: 1px black solid; } .node:nth-child(2)::before { transform: rotate(60deg); } .node:nth-child(3)::before { transform: rotate(120deg); } .node:nth-child(4)::before { transform: rotate(180deg); } .node:nth-child(5)::before { transform: rotate(240deg); }
<div class="node"> 1 </div> <div class="node"> 2 </div> <div class="node"> 3 </div> <div class="node"> 4 </div> <div class="node"> 5 </div>
这样每个.node内的六边形背景就会按60度递增旋转,虚线会依次出现在不同侧边上。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

