【问题标题】:Gradient border on MUI componentMUI 组件上的渐变边框
【发布时间】:2021-07-03 19:59:31
【问题描述】:

我没有找到border-image-source css 的等价物

我的目标是在按钮组件上渲染边框渐变

【问题讨论】:

    标签: css reactjs material-ui jss makestyles


    【解决方案1】:

    这是为button 组件添加渐变边框的方法:

    V5

    const options = {
      shouldForwardProp: (prop) => prop !== 'gradientColors',
    };
    
    const GradientButton = styled(
      Button,
      options,
    )(({ theme, gradientColors }) => ({
      border: '5px solid',
      borderImageSlice: 1,
      borderImageSource: `linear-gradient(to left, ${gradientColors.join(',')})`,
    }));
    

    如果你想要一个带有渐变边框的圆形按钮,你不能使用上面的代码,因为borderImagedoesn't have a radius。一种解决方法是在子元素 :after 中创建渐变背景,因为可以使用 borderRadius 剪切 background

    const borderRadius = 15;
    const RoundGradientButton = styled(
      Button,
      options,
    )(({ theme, gradientColors }) => ({
      position: 'relative',
      border: '5px solid transparent',
      backgroundClip: 'padding-box',
      borderRadius,
    
      '&:after': {
        position: 'absolute',
        top: -5,
        left: -5,
        right: -5,
        bottom: -5,
        background: `linear-gradient(to left, ${gradientColors.join(',')})`,
        content: '""',
        zIndex: -1,
        borderRadius,
      },
    }));
    

    用法

    <GradientButton gradientColors={['red', 'yellow']} variant="contained">
      Default
    </GradientButton>
    <RoundGradientButton gradientColors={['red', 'yellow']} variant="contained">
      Default
    </RoundGradientButton>
    

    现场演示

    V4

    const useStyles = makeStyles((theme: Theme) => ({
      button: {
        border: "6px solid",
        borderImageSlice: 1,
        borderImageSource: "linear-gradient(to left, red, orange)"
      }
    }));
    
    export default function ContainedButtons() {
      const classes = useStyles();
    
      return (
        <Button className={classes.button} variant="contained">
          Default
        </Button>
      );
    }
    

    现场演示

    相关答案

    【讨论】:

    • 您知道如何添加边框半径吗?因为borderRadius 不使用borderImageSource
    • @seserize 见this 答案,我已经为你更新了现场演示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多