You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS rotate()旋转轴疑问:代码为何生成正方形而非十字?

问题:为何旋转线条生成正方形而非十字?

我参考别处代码编写,预期生成绿色十字线条,但运行后却得到正方形效果。看起来所有线条的旋转轴似乎不同,请问为何无法生成十字而是正方形?

代码:

import styled from "styled-components";

export default function App() {
  const array = [0, 1, 2, 3];

  return (
    <Wrap>
      <div className="container">
        <div className="square">
          {array.map((idx) => {
            return <Line number={idx} />;
          })}
        </div>
      </div>
    </Wrap>
  );
}

const Wrap = styled.div`
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
  background: #111;

  .container {
    border: 3px solid orange;
    position: relative;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .container .square {
    top: 200px;
    left: 200px;
    border: 1px solid blue;
    position: absolute;
    width: 200px;
    height: 200px;
  }
`;

const Line = styled.span`
  border: 1px solid red;
  position: absolute;
  inset: 10px;
  transform: ${(props) => `rotate(calc(90deg * ${props.number}))`};

  &::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 4px;
    background: #0f0;
  }
`;

问题原因

你得到正方形而非十字的核心问题在于:

  • Line元素通过inset:10px被设置成了一个180x180的方块,而非单纯的线条容器。
  • 你旋转的是整个方块,伪元素::before作为方块的子元素,会跟着方块的旋转改变方向:
    • 0度旋转时,伪元素是方块顶部的水平横线;
    • 90度旋转时,方块整体转向,伪元素变成方块右侧的垂直竖线;
    • 180度和270度同理,最终四个伪元素刚好组成正方形的四条边。

修复方案

调整Line元素的定位和旋转逻辑,让它成为线条的基线,而非方块:

  1. 移除inset:10px,改为让Line水平铺满左右(除10px边距)、垂直居中父容器;
  2. 合并垂直居中和旋转的变换逻辑,确保旋转原点为元素中心;
  3. 可选优化:数组只保留[0,1]即可,因为180/270度的线条和0/90度完全重合,无需重复渲染。

修改后的Line样式:

const Line = styled.span`
  position: absolute;
  top: 50%;
  left: 10px;
  right: 10px;
  /* 先垂直居中,再执行旋转 */
  transform: translateY(-50%) ${(props) => `rotate(calc(90deg * ${props.number}))`};
  /* 显式声明旋转原点为元素中心(默认值,但更清晰) */
  transform-origin: center;

  &::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 4px;
    background: #0f0;
  }
`;

修改后的数组:

const array = [0, 1];

这样就能得到你想要的绿色十字线条了。


内容的提问来源于stack exchange,提问作者DgUZH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:33:19