CSS Height and Width

The width and height properties set the size of an element's content box using lengths, percentages, or keywords.

The <width> and <height> properties define how much space an element's content area takes up. They apply to block-level and inline-block elements, but not to plain inline elements like a span.

Units you can use

  • Pixels (px) for a fixed size that never changes.
  • Percentages (%) that are relative to the parent element's size.
  • Viewport units (vw and vh) that scale with the browser window.
  • The keyword auto, which lets the browser calculate the size.

Fixed and relative sizing

<!DOCTYPE html>
<html>
<head>
<style>
.banner {
  width: 100%;
  height: 240px;
}

.thumbnail {
  width: 150px;
  height: 150px;
}
</style>
</head>
<body>

<div class="banner">Banner</div>
<div class="thumbnail">Thumb</div>

</body>
</html>

Height can be tricky

A percentage width works against the parent's width without any extra setup, but a percentage height only works if the parent has an explicit height. Otherwise the parent is only as tall as its content and the percentage has nothing to measure against.

Full-height section

<!DOCTYPE html>
<html>
<head>
<style>
html, body {
  height: 100%;
}

.hero {
  height: 100vh;
}
</style>
</head>
<body>

<div class="hero">
  <h1>Welcome</h1>
</div>

</body>
</html>
Note: Remember that width and height set the content box by default. Padding and border add to the total unless you use box-sizing: border-box.

To keep an element within a size range instead of a single fixed value, see CSS Min and Max Size.