CSS Height and Width

The width and height properties set the size of the content area of an element. Block elements are as wide as their parent by default, and as tall as their content.

.box {
  width: 300px;
  height: 100px;
  background: lightgreen;
}
Output in the browser
300px x 100px


Width in percent

A percentage is calculated from the width of the parent.

.half { width: 50%; }

max-width and min-width

A fixed width can break the layout on a small phone, because the box cannot shrink. Use max-width: the box can be smaller, but never bigger than the limit.

.container {
  width: 100%;
  max-width: 960px;
  margin: 0 auto;      /* centre the box */
}
  • max-width sets the biggest width.
  • min-width sets the smallest width.
  • max-height and min-height do the same for height.

Height

Avoid giving a fixed height to boxes with text. If the text grows, it will come out of the box. Use min-height instead.

.section { min-height: 200px; }
.full { height: 100vh; }   /* full screen height */
Note: By default width does not include padding and border, so a box with width: 200px and padding: 20px becomes 240px wide. Fix this with box-sizing: border-box. See CSS Box Model.

Summary

  • width and height set the size.
  • Prefer max-width and min-height for flexible layouts.
  • Centre a box with margin: 0 auto and a width.
  • Next: CSS Padding.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.