Why Doesn't This CSS Transition Work On SVG Inside an Anchor

落爺英雄遲暮 提交于 2019-11-29 00:12:33
Zach Saucier

The reason why the transition doesn't work is because it is within a link.

To fix it, put the link inside of the SVG instead like this SO post suggests

OR

Make the SVG a sibling of the link and use the sibling selector

/* This goes within `a { ...` */
&:hover + svg { /* Or use ~ to select all */
  .the-background
  {
    fill: black;
  }

  .the-icon
  {
    fill: red;
  } 
}

The way I solved this problem was to place fill="currentColor" on the svg path element that I wanted to transition. Then I added color and transition properties to the surrounding anchor tag and performed the CSS transition on the anchor tag instead of the svg path itself. Below is a very stripped down example:

HTML:

<a>
    <svg>
        <path fill="currentColor" />
    </svg>
</a>

SCSS:

a { color: black; transition: color .2s linear;
    &:hover { color: white; } }

I just discovered that in order to transition an svg fill within an anchor element, it only works using rgba color codes. I haven't researched why that is, but it's working on my projects - here's an example: http://rawesome.leveragenewagemedia.com/ (hover the social media icons).

Here's the SASS I'm using:

.icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  fill: rgba(0,0,0,.2);
  -webkit-transition: fill .5s;
  -moz-transition: fill .5s;
  -ms-transition: fill .5s;
  -o-transition: fill .5s;
  transition: fill .5s;

  &:hover {
    fill: rgba(0,0,0,.5);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!