コードサンプルも含まれている、より理解しやすい回答を求めてここに来る人にとって、この回答(ここからコピー)はあなたにぴったりです。
JavaScriptや明確なピクセル値(など)は必要ありません100px
。純粋なCSSとパーセンテージだけです。
あなたのdivがそれだけでそこに座っている場合height: 50%
、体の高さの50%を意味します。通常、体の高さは目に見えるコンテンツがない場合はゼロであるため、その50%はちょうどゼロです。
これが解決策です(これに基づいています)(行のコメントbackground
を外してパディングを視覚化します):
/* Makes <html> take up the full page without requiring content to stretch it to that height. */
html
{
height: 100%;
/* background: green; */
}
body
{
/*
100% the height of <html> minus 1 multiple of the total extra height from the padding of <html>.
This prevents an unnecessary vertical scrollbar from appearing.
*/
height: calc(100% - 1em);
/* background: blue; */
}
/* In most cases it's better to use stylesheets instead of inline-CSS. */
div
{
width: 50%;
height: 50%;
background: red;
}
<div></div>
上記は、通常のパディングが引き続き存在するように作成されています。赤の寸法をに設定してdiv
も100%
、両側/端にパディングが表示されます。このパディングが必要ない場合は、これを使用してください(見栄えは良くありませんが、最初の例を使用することをお勧めします)。
/* Makes <html> take up the full page without requiring content to stretch it to that height. */
html, body
{
height: 100%;
}
/* You can uncomment it but you wouldn't be able to see it anyway. */
/*
html
{
background: green;
}
*/
body
{
margin: 0;
/* background: blue; */
}
/* In most cases it's better to use stylesheets instead of inline-CSS */
div
{
width: 50%;
height: 50%;
background: red;
}
<div></div>