0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【CSS】背景色がスライドするボタン

Posted at

はじめに

CSSについて勉強中です。勉強で理解したことを備忘録として残しておきます。
今回はCSSを使って背景色がスライドするボタンを作成しました。

ボタンの表示

gif.gif

ファイル内容

作成したHTMLファイルとCSSファイルです。設定したスタイルの内容は後で説明します。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="container">
      <button class="btn slide-bg"><span></span>Button</button>
    </div>
  </body>
</html>
#container {
  text-align: center;
}
.btn {
  background-color: white;
  color: black;
  border: 1px solid black;
  padding: 10px 40px;
  margin: 50px 0;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}
.btn.slide-bg {
  position: relative;
  overflow: hidden;
  z-index: 1;
}
.btn.slide-bg span {
  display: inline-block;
  width: 100%;
  height: 100%;
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  transform: translateX(-100%);
  transition: transform 0.3s;
  z-index: -1;
}
.btn.slide-bg:hover {
  color: white;
}
.btn.slide-bg:hover span {
  transform: none;
}

HTMLファイル内容

<button class="btn slide-bg">
  <span></span>Button
</button>
  • span要素は、アニメーション用の背景
  • buttonの中に入れて、背景がスライドするようにしている

CSSファイル内容

ボタンのベーススタイル

.btn {
  background-color: white;
  color: black;
  border: 1px solid black;
  padding: 10px 40px;
  margin: 50px 0;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}
  • 白背景 + 黒文字のシンプルなボタンにしている
  • transition: all 0.3s で滑らかな変化をつける

背景スライド用の設定

.btn.slide-bg {
  position: relative;
  overflow: hidden;
  z-index: 1;
}
  • position: relative;:子要素(span)を絶対配置するための基準
  • overflow: hidden;:ボタン外に背景がはみ出さないようにする
  • z-index: 1;:文字が背景より前に出るようにする

スライドさせる背景

.btn.slide-bg span {
  display: inline-block;
  width: 100%;
  height: 100%;
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  transform: translateX(-100%);
  transition: transform 0.3s;
  z-index: -1;
}
  • position: absolute;:ボタンの中に広がるように配置
  • transform: translateX(-100%):初期状態でボタンの左に完全はみ出るように移動している
  • z-index: -1;:背景になるように、文字よりも後ろに表示

ホバー時の変化

.btn.slide-bg:hover {
  color: white;
}
.btn.slide-bg:hover span {
  transform: none;
}
  • 文字色が白に変化
  • spanがボタン内にスライドして、背景が黒に切り替わる

おわりに

CSSの細かい設定は調べたり値を変化させたりしてみると理解が深まると思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?