SVG gradient using CSS

前端 未结 6 1275
粉色の甜心
粉色の甜心 2020-11-29 19:58

I\'m trying to get a gradient applied to an SVG rect element.

Currently, I\'m using the fill attribute. In my CSS file:

rec         


        
6条回答
  •  半阙折子戏
    2020-11-29 20:27

    Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.

    This is what you need to do:

    1. Assign classes to each color stop defined in the gradient element.
    2. Target the css and change the stop-color for each of those stops using plain classes.
    3. Win!

    Some benefits of using classes instead of :nth-child is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.

    I've tested it on all Chrome, Firefox and IE11:

    .main-stop {
      stop-color: red;
    }
    .alt-stop {
      stop-color: green;
    }
    
      
        
        
      
      
    

    See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output

提交回复
热议问题