LoginSignup
1
0

要素同士を重ねて表示する方法

Posted at

こんには!
今回は要素同士を重ねて表示するレイアウトについて
書いていこうと思います💭

今回紹介するのは
position: absolute;position: relative; です!

position: absolute;とは?

HTMLの要素同士は通常は重なって表示されることはありません。
しかし、position: absolute;を使うと要素同士を重ねて表示させることができます。

サイト全体の左上の部分を基準として、そこからの位置をtopとleftを用いて指定してあげます。  
また、rightやbottomを併用することも可能です。

実際に例を挙げると。。。

index.html
  <body>
      <div class="box1">box1</div>
      <div class="box2">box2</div>
  </body>

position指定なしの場合

style.css
.box1{
  background: orange;
  width: 300px;
  height: 300px;
}

.box2{
  background-color: aqua;
  width: 300px;
  height: 300px;
}

スクリーンショット 2023-05-30 111215.png

こんな感じになります。

positionを指定ありの場合

stile.css
.box1{
  background: orange;
  width: 300px;
  height: 300px;
  position: absolute;
  top: 50px;
  left: 70px;
}

.box2{
  background-color: aqua;
  width: 300px;
  height: 300px;
  position: absolute;
  top: 120px;
  left: 140px;
}

スクリーンショット 2023-05-30 112532.png

こんな感じで画面の左上を基準としてbox1とbox2を重ねて表示させてあげることができました。

基準位置の変更

position: absolute;の基準位置はサイト全体の左上部分ですが、この基準位置を変更することも可能です!

基準としたい親要素にposition: relative; を指定すると、その要素の左上部が基準位置になります。

box1を基準位置にして要素を重ねた場合

style.css
.box1{
  background: orange;
  width: 300px;
  height: 300px;
  position: relative;
}

.box2{
  background-color: aqua;
  width: 200px;
  height: 200px;
  position: absolute;
  top: 30px;
  left: 30px;
}

スクリーンショット 2023-05-30 114055.png

こんな感じでbox1の左上を基準としてbox2が配置されるようになりました。

今回は簡単な重ね方ですが、この方法を使っていろんなレイアウトができるかなって思います!

そんなに出番はないかもしれないけど  
引き出しとして覚えておきたいレイアウトの一つでした✨

今回はこのへんで!
ありがとうございました。

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