CSS Height and Width

Fixed Dimensions

You can use absolute units like px, cm, or in to define a static box size.

div {
  width: 300px;
  height: 150px;
}

Percentage Dimensions

Percentages are calculated relative to the parent element's dimensions.

div {
  width: 80%;
  height: 50%;
}

Viewport Units

Viewport units size elements relative to the size of the browser window (the viewport), making them very useful for creating responsive layouts.

  • vw – Viewport width. 1vw equals 1% of the width of the viewport.
  • vh – Viewport height. 1vh equals 1% of the height of the viewport.
  • vmin – The smaller value of vw or vh. Useful for keeping proportions in portrait or landscape modes.
  • vmax – The larger value of vw or vh. Helps scale elements based on the largest viewport dimension.

Example using vw and vh:

div {
  width: 50vw; /* Half the width of the viewport */
  height: 30vh; /* 30% of the viewport's height */
}

Min and Max Values

Set constraints to prevent elements from becoming too small or large:

div {
  min-width: 200px;
  max-width: 500px;
}

Auto Value

The default behavior is auto, where height adjusts based on content.

div {
  height: auto;
}

Practice Prompt

Try creating two styled boxes:

<div style={{
  width: "300px",
  height: "150px",
  backgroundColor: "#ffd700",
  marginBottom: "20px"
}}>
  Fixed size box
</div>

<div style={{
  width: "80%",
  height: "30vh",
  backgroundColor: "#90ee90"
}}>
  Responsive size box
</div>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic