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?

More than 1 year has passed since last update.

CSS positon使い方

Posted at

positionとは

要素の意図を決める際に使用するプロパティ

要素の位置はmergin,paddingなどでも決めれるが、positionを使うことで
・要素を重ねる
・要素を固定する
などより柔軟なレイアウト作成が可能となる

positionで指定できる値

  • position: relative
  • position: absolute
  • position: fixed
  • position: static
  • position: sticky

→単体だけではあまり使わない
位置を決めるために使用するため、位置表示の値を一緒に使用する

position: relative

・相対的な位置指定ができる
→要素の動的な配置に使用される

要素は、通常のHTMLの流れに従って配置される
top、bottom、left、rightプロパティで位置を微調整することができる

position: absolute

・最寄りの親要素(positionがstaticでない要素)に対して配置される
→要素を重ねて表示したい場合に使用される

top、bottom、left、rightプロパティで位置を指定できる

  • 親要素がない場合:ブラウザウィンドウの左上隅に対して配置される

position: fixed

ブラウザウィンドウの左上隅に対して配置される
スクロールしても、要素はその位置に留まる
→画面上の固定位置に配置する場合に使用される
EX)要素をヘッダーやフッターなど

position: static

デフォルト値で、要素は通常のHTMLの流れに従って配置される
top、bottom、left、rightプロパティは影響を受けない

position: sticky

要素をスクロール時に固定された位置に配置するためのプロパティ

要素は一定の位置までスクロールされたときに固定
→通常のHTMLの流れに従って配置される

.container {
  height: 500px;
  overflow-y: scroll;
}

.sticky {
  position: sticky;
  top: 0;
}

.containerクラスに
heightプロパティ
overflow-yプロパティ
が設定されている

→.container要素がスクロール可能

.stickyクラス
position: stickyとtop: 0が設定されている
→.sticky要素が上部に固定され、.container要素がスクロールされると、.sticky要素がその位置に留まる


要素の位置をスクロールに応じて動的に変更できる
また、複数の方向に設定することもできる

EX)leftプロパティを設定

.sticky {
  position: sticky;
  top: 0;
  left: 0;
}

→.sticky要素がスクロール時に上部に固定されるだけでなく、左端にも固定される

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?