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

如何在styled-components样式的div中绘制十字图形?

解决方案:用双伪元素实现十字对角线

你可以通过**:before和:after两个伪元素**分别绘制两条对角线,调整旋转角度和变换原点就能避免位置异常。以下是修改后的完整StyledCell代码:

export const StyledCell = styled.div`
    width: auto;
    background: rgba(${props => props.color}, 0.1);
    border: ${props => (props.type === 0 ? '0px solid' : '4px solid')};
    border-bottom-color: rgba(${props => props.color}, 0.5);
    border-right-color: rgba(${props => props.color}, 1);
    border-top-color: rgba(${props => props.color}, 1);
    border-left-color: rgba(${props => props.color}, 0.7);
    position: relative;

    /* 左上到右下的对角线 */
    &:after{
        content:"";
        position:absolute;
        border-top:1px solid red;
        width: calc(100% * 1.414); /* 对角线长度=边长×√2,适配容器尺寸 */
        top: 0;
        left: 0;
        transform: rotate(45deg);
        transform-origin: 0% 0%; /* 以左上角为旋转原点 */
    }

    /* 右上到左下的对角线 */
    &:before{
        content:"";
        position:absolute;
        border-top:1px solid red;
        width: calc(100% * 1.414);
        top: 0;
        right: 0;
        transform: rotate(-45deg);
        transform-origin: 100% 0%; /* 以右上角为旋转原点 */
    }
`;

核心调整点:

  • 用两个伪元素分离两条对角线,避免样式冲突
  • 用calc(100% * 1.414)替代固定的40px,让线条长度自适应容器(√2是正方形对角线的比例系数,非正方形可根据宽高调整)
  • 分别设置transform-origin为左上角和右上角,配合对应旋转角度,确保两条线在容器中心交叉形成十字

如果需要调整线条的颜色、粗细或位置,直接修改伪元素的border-top、top/left/right属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:12:43