LoginSignup
0
0

More than 5 years have passed since last update.

<html>,<body>に指定したmarginの合計値分ページ周りに余白が出る

Posted at

<html><body>はなんだか特別な感じのするタグだと思っているので、「2つともmargin: 10px;にしたら周りが20px空いてる!!」と驚いていたのですが、marginの仕様を考えると当たり前のことでした。
margin - CSS | MDN

実際に測ってみる

index.html
<!-- 省略 -->
<body>
 <div id="main"></div>
 <div id="box1"></div>
 <div id="box2"></div>
 <div id="box3"></div>
 <div id="box4"></div>
</body>
<!-- 省略 -->
style.css
html {
  margin: 10px;
  height: 100%;
}

body {
  margin: 20px;
  height: 100%;
}

#main {
  width: 100%;
  height: 100%;
  background-color: red;
}

/* 配置によってwidthやheightにhtml,bodyのmarginの合計値を指定、
余白に関係ない方は任意の値 */

#box1 {
  width: 30px;
  height: 300px;
  background-color: blue;
  top: 0;
  left: 0;
  position: absolute;
}

#box2 {
  width: 300px;
  height: 30px;
  background-color: green;
  top: 0;
  left: 0;
  position: absolute;
}

#box3 {
  width: 300px;
  height: 30px;
  background-color: yellow;
  left: 0;
  bottom: -60px;
  position: absolute;
}

#box4 {
  width: 30px;
  height: 300px;
  background-color: gray;
  top: 0;
  right: 0;
  position: absolute;
}

<html><body>height: 100%;としているのは#mainheight: 100%;を使えるようにするためです。
"height: 100%" の要素が画面の高さ100%にならない場合の対応方法

これをブラウザで確認すれば、#mainの周りの余白に#boxたちがきれいに収まっていると思います。このことからタイトルの内容は正しいと言えそうです。

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