LoginSignup
12
8

More than 5 years have passed since last update.

background-imageはanimationやtransitionで動かせない

Last updated at Posted at 2018-10-01

CSSのbackground-imageプロパティはanimationやtransitionを使って動かせません。

しかし、アニメーションで動かせないと聞くとかえって動かしたくなりませんか?特にホバーするとふわりとグラデーションするボタンとか作りたくないですか?(謎の圧)

まずはこちらをご覧ください。

See the Pen Button with Gradient Effect by Hibiki Kudo (@h_kudo) on CodePen.



ホバーすると背景がグラデーションするものの、仕様通りtransition-durationプロパティが無視されアニメーション効果がついてくれません。

そこでopacityプロパティと擬似要素を使ってふわりと背景が遷移するアニメーションを表現します。

See the Pen Button with Animated Gradient Effect by Hibiki Kudo (@h_kudo) on CodePen.



コードはこちら
button.html
<button type="button" class="button"><span class="button__inner">Hover me</span></button>
style.css
.button {
  position: relative;
  display: inline-block;
  overflow: hidden;
  width: auto;
  min-width: 120px;
  height: 50px;
  padding: 0;
  border: none;
  border-radius: 8px;
  background-color: #da0641;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
}
.button::after {
  position: absolute;
  z-index: 0;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: "";
  transition-duration: .3s;
  opacity: 0;
  background-image: linear-gradient(135deg, #f2d50f 0%, #da0641 100%);
}
.button:hover {
  cursor: pointer;
}
.button:hover::after {
  opacity: 1;
}
.button__inner {
  font-size: 20px;
  position: relative;
  z-index: 2;
  display: flex;
  min-width: 120px;
  height: 100%;
  padding: 0 15px;
  text-decoration: none;
  color: #fff;
  justify-content: center;
  align-items: center;
}

この小技で少し遊び心を感じるふわっとグラデーションするボタンが実装できました。

12
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8