Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8589

position:relative な要素が overflow:auto領域にあるときスクロールバーが出る問題を解決する

$
0
0

解決したい課題

あるdiv要素の上に、position:relativeな要素をオーバーレイ表示させたいとします。
(例: 地図の上にツールバーを表示させたい、など)

このとき両要素の親要素にoverflow:autoが設定されていると、見た目上は要素が範囲内におさまっているのにスクロールバーが出るという現象が起きます。

scrollbar.gif

overflow:hiddenにできればいいのですが、ウィンドウを縮小されたときなどにはスクロールバーが必要になります。

overflow:autoは維持したまま、不要なスクロールバーを非表示にしたい。

<divclass="container"><divclass="text">
    This content should not have a vertical scrollbar.
  </div><divclass="relative"></div></div>
.container{width:500px;height:200px;margin:10px;border:2pxsolidblue;overflow:auto;}.text{width:90%;height:80%;padding:10px;border:2pxsolidblack;margin:5px;}.relative{width:50px;height:50px;bottom:80px;left:80px;position:relative;border:2pxsolidred;background-color:red;}

解決策

以下のコードのように、position:relative要素にラッパーを用意し、ラッパーをheight:0pxに設定すると、不要なスクロールバーをなくすことができます。

<divclass="container"><divclass="text">
    Relative wrapper class can avoid the scrollbar.
  </div><divclass="relative-wrapper"><divclass="relative-inner"></div></div></div>
/* Trick! */.relative-wrapper{height:0px;bottom:80px;left:80px;position:relative;}.relative-inner{width:50px;height:50px;border:2pxsolidred;background-color:red;}

紹介したコードは以下のCodepenで動かせますので、よろしければ覗いてみてください。
Avoid scroll bar with a relative element in overflow:auto area


Viewing all articles
Browse latest Browse all 8589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>