Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS transition ignores width

I have an tag which is displayed as a block. On page load, its width is increased by a css animation from zero to some percentage of the containing div (the fiddle contains a MWE, but there is more than one link in this div, each with a different width). On hover, I want it to change colour, change background colour, and also expand to 100% of the div, using a CSS transition. The colour and background colour bit is working, but it seems to ignore the width transition.

Snippet:

.home-bar {
  text-decoration: none;
  background-color: white;
  color: #5e0734;
  display: block;
  -webkit-animation-duration: 1.5s;
  -webkit-animation-timing-function: ease-out;
  -webkit-animation-fill-mode: forwards;
  animation-duration: 1.5s;
  animation-fill-mode: forwards;
  transition: color, background-color, width 0.2s linear;/*WIDTH IGNORED*/
  border: 2px solid #5e0734;
  overflow: hidden;
  white-space: nowrap;
  margin-right: 0;
  margin-left: 5px;
  margin-top: 0;
  margin-bottom: 5px;
  padding: 0;
}

.home-bar:hover {
  background-color: #5e0734;
  color: white;
  width: 100%;/*WIDTH IGNORED*/
  text-decoration: none;
}

#bar0 {
  -webkit-animation-name: grow0;
  animation-name: grow0;
}

@keyframes grow0 {
  from {
    width: 0%;
  }
  to {
    width: 75%;
  }
}
<a href="#" id="bar0" class="home-bar">LINK</a>

Note - I've tested it with changing the height of the link on hover, and it worked. Only the width does not work. Perhaps it has something to do with the animation on page-load.

like image 439
Alex Avatar asked Apr 30 '18 10:04

Alex


1 Answers

When you set width using animation you will override any other width defined with CSS inluding the one defined by hover. The styles inside a keyframes is more specific than any other styles:

CSS Animations affect computed property values. This effect happens by adding a specified value to the CSS cascade ([CSS3CASCADE]) (at the level for CSS Animations) that will produce the correct computed value for the current state of the animation. As defined in [CSS3CASCADE], animations override all normal rules, but are overridden by !important rules. ref

A workaround is to consider both width/max-width properties to avoid this confusion:

.home-bar {
  text-decoration: none;
  background-color: white;
  color: #5e0734;
  display: block;
  animation: grow0 1.5s forwards;
  transition: color, background-color, max-width 0.2s linear;
  border: 2px solid #5e0734;
  max-width: 75%; /*Set max-wdith*/
}

.home-bar:hover {
  background-color: #5e0734;
  color: white;
  max-width: 100%; /* Update the max-width of hover*/
  text-decoration: none;
}

/*Animate width to 100%*/
@keyframes grow0 {
  from {
    width: 10%;
  }
  to {
    width: 100%;
  }
}
<a href="#" id="bar0" class="home-bar">LINK</a>
like image 118
Temani Afif Avatar answered Sep 17 '22 12:09

Temani Afif