Episode 41 of 53

Width and Height

Learn how to control element dimensions with width, height, and related properties.

The width and height properties control the dimensions of block-level and inline-block elements.

Basic Usage

.box {
    width: 300px;
    height: 200px;
    background: #3498db;
}

Units

  • px — fixed pixels
  • % — percentage of parent's width/height
  • vw/vh — percentage of viewport
  • rem/em — relative to font size

Min and Max

.container {
    width: 90%;
    max-width: 1200px;   /* Never wider than 1200px */
    min-width: 320px;    /* Never narrower than 320px */
    margin: 0 auto;
}

.card {
    min-height: 200px;   /* At least 200px tall */
    max-height: 400px;   /* At most 400px tall */
    overflow: auto;      /* Scroll if content overflows */
}

Auto

img {
    width: 100%;
    height: auto;  /* Maintain aspect ratio */
}

Important Notes

  • Inline elements ignore width/height — use display: inline-block or display: block
  • With box-sizing: border-box, width includes padding and border
  • Prefer max-width over fixed width for responsive design