要素を固定する position: fixed;

要素を固定する position: fixed;

positionプロパティを使って要素位置を固定するfixed
  • コンテンツを画面に固定させて表示させたい場合に利用します
  • positionプロパティはfixedの他にも下記の4つがあります
    • relative
    • absolute
    • static
    • sticky
position: fixed;の使い方
  • positionプロパティは、要素の配置を指定するプロパティです
  • positionプロパティの初期値はstaticで、fixedは要素位置を固定することができます
セレクタ {
  position: fixed;
  top: 値;
  right: 値;
  bottom: 値;
  left: 値;
}
  • positionプロパティは「top」「right」「bottom」「left」の4つのプロパティと合わせて要素の配置を指定します
  • 要素の位置を確定させるため、最低でも2つは適用するようにします
  <div class="fixed">このエリアが固定</div>
  <div class="content">
    <p>1行目のテキストが入る</p>
    <p>2行目のテキストが入る</p>
    <p>3行目のテキストが入る</p>
    <p>4行目のテキストが入る</p>
    <p>5行目のテキストが入る</p>
  </div>
* {
  margin: 0;
  padding: 0;
}
.fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  background-color: #ffa500;
}
.content {
  width: 100%;
  height: 2000px;
  margin-top: 80px;
  background-color: #87ceeb;
}



z-indexプロパティで重なり順を指定する
  • positionプロパティはstaticを除いて、重なり順を指定するz-indexプロパティを指定することができます
.fixed {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;  /* 追記 */
  width: 100%;
  height: 80px;
  background-color: #ffa500;
}
  • z-index: -1; を適用したことによって、fixedクラスの要素はcontentsクラス要素の裏側に配置されました
  • z-indexは、値の数字が大きいほど前に、小さいほど後ろに配置されます