LoginSignup
3
1

More than 1 year has passed since last update.

CSSでスクロールバーを常時表示する

Last updated at Posted at 2021-12-18

概要

下記のようなX方向のスクロールバーを実装したとき、トラックパッドがない人は←→キーを押さないとスクロールができない。

実装

以下のようにCSSを当てればスクロールバーを常に表示できる。

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" />
  </head>

  <body>
    <div class="container">
      <div 
    class="
      content
      scrollbar
      scrollbar-thumb-rounded
      scrollbar-thumb-black
    "
      >
        <div class="color">
          color
        </div>
      </div>
    </div>
  </body>
</html>
src/style.css
body {
  font-family: sans-serif;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
}

.content {
  position: relative;
  width: 200px;
  height: 200px;
  overflow-x: scroll;
}

.color {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0px;
  left: 0;
  width: 800px;
  height: 190px;
  color: white;
  background: linear-gradient(0.25turn, red, 50%, blue);
}

/* スクロールバーの幅と高さを設定する */
.scrollbar::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/* スクロールバーの形を設定する */
.scrollbar-thumb-rounded::-webkit-scrollbar-thumb {
  border-radius: 0.25rem;
}
/* スクロールバーの色を設定する */
.scrollbar-thumb-black::-webkit-scrollbar-thumb {
  --bg-opacity: 1;
  background-color: black;
}

ポイントはこちらのCSSです。

/* スクロールバーの幅と高さを設定する */
.scrollbar::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/* スクロールバーの形を設定する */
.scrollbar-thumb-rounded::-webkit-scrollbar-thumb {
  border-radius: 0.25rem;
}
/* スクロールバーの色を設定する */
.scrollbar-thumb-black::-webkit-scrollbar-thumb {
  --bg-opacity: 1;
  background-color: black;
}

-webkit-scrollbarでスクロールバーに比較的自由にCSSを当てることがきます。ただ-webkit-scrollbarはwebkit系のブラウザにしか対応していないためIEやfirefoxでは適用できない点に注意してください。

3
1
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
3
1