2
1

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 3 years have passed since last update.

[HTML / CSS] 絶対位置と相対位置

Posted at

はじめに

Webアプリのフロントをいじっているときに、「絶対位置」と「相対位置」って、要素を自分の思った通りの配置に置きたい時にすごい大事だなと思いまして、自分になりにまとめてみました。

よろしくお願いします。

positionプロパティ

positionプロパティは要素の配置を指定できるプロパティです。このプロパティを使いこなすのには絶対位置と相対位置の理解が必要不可欠です。

今回はposition: absolute;とposition: relative; の使い方を見ていきながら絶対位置と相対位置の理解を深めていきたいと思います。

絶対位置

まず、下記のようなHTMLとCSSがあるとします。

index-position.html
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="UTF-8">
    <title>position</title>
    <link rel="stylesheet" href="style-position.css">
  </head>
  <body>
    <header></header>
    <div class="main">
      <div class="parent">
        <div class="child">
        </div>
      </div>
    </div>
    <footer></footer>
  </body>
</html>
style-position.css
header{
  height: 80px;
  width: 100%;
  background-color: lightgray;
}

.main{
  color: white;
}

.parent{
  width :360px;
  height: 360px;
  background-color: pink;
  margin: 40px;
}

.child{
  width :200px;
  height: 200px;
  background-color: skyblue;
}

footer{
  height: 80px;
  width: 100%;
  background-color:lightgray;
}

これをブラウザで表示させてみるとこのようになります↓

image.png

そしたら、position: absolute;を使ってみましょう。
positionプロパティを使ったら、leftプロパティやtopプロパティを使って基準の位置からの距離も指定してあげます。
※この指定がなければposition: absolute;を使っても反映されません

childのcssを下記のように修正してください。

style-position.css
.child{
  width :200px;
  height: 200px;
  background-color: skyblue;
  position: absolute;
  top: 40px;
  left: 40px;
}

そうするとこのようになるはずです↓
image.png

基準が一番左上でtopとleftで40px指定しているので40pxの余白があります。
これが絶対位置です。例え、親要素の中に含まれている子要素でも、絶対位置に指定するとそこからはみ出て絶対位置に配置されます。

相対位置

ある要素が他の要素との関係の上に成り立つ位置のことを相対位置と言います。

親要素のほうにposition: relative;を追加します。

style-position.css
.parent{
  width :360px;
  height: 360px;
  background-color: pink;
  margin: 40px;
  position: relative;
}

そうすると子要素は親要素の左上を基準にするようになり、相対位置をとります。↓
image.png

親要素にposition:relative;を指定することで、position:absolute;を指定されている子要素の基準位置が、親要素になりました。これが相対位置です。

最後に

要素を配置する時私は十中八九反映されなかったり、思った通りの場所へ動いてくれなかったりします。
それぞれのプロパティの意味などもしっかり理解して、フロントも強いエンジニアになりたいです。

そういえば、positionプロパティとは関係ないですが、プロパティの意味を勘違いしてた記事がありました、こちらの記事もよかったらどうぞ。
https://qiita.com/minhee/items/76e05c7537d2389a0ef6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?