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?

CSS position:absoluteが思い通りに動かない原因と解決法(relativeの使い方)

0
Posted at

はじめに

position:absoluteが思い通りに動かず、
意図しない場所に配置されてしまうことがありました。

問題

以下のように要素を配置した際、
position:absoluteを使っているのに
意図した位置に配置されませんでした。

原因

position:absoluteは、通常は画面全体(body)を基準に配置されます。

しかし、親要素にposition:relativeが指定されていない場合、
意図しない位置に配置されてしまいます。

解決法

親要素にposition:relativeを指定することで、
その要素を基準に配置できるようになります。

コード

.contents{
  width: 500px;
  position: relative;
}

.card1{
  height: 250px;
  width: 300px;
  background-color: lightcoral;
  text-align: center;
  position: absolute;
  top: 40px;
  left: 40px;
}

.card2{
  height: 250px;
  width: 300px;
  background-color: lightblue;
  text-align: center;
  position: absolute;
  top: 120px;
  left: 60px;
}

.card3{
  height: 250px;
  width: 300px;
  background-color: lightgreen;
  text-align: center;
  position: absolute;
  top: 200px;
  left: 80px;
}

ハマったポイント

marginで位置を調整しようとしていたが、
positionによる位置指定とは役割が異なるため、
思った通りに動かなかった。

まとめ

position:absoluteは、
「どこを基準に配置されるのか」を理解することが重要でした。

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?