CSS Height and Width

Subject: css

CSS Height and Width

The height and width properties in CSS are used to control the size of HTML elements. These properties are commonly applied to block-level elements (like <div> or <section>) and some inline-block elements to define their visible space.


Common Units for Height and Width

You can use various units with height and width:

  • px: Pixels (absolute unit)
  • %: Percentage relative to the parent element
  • em / rem: Relative to the font size of the element or root
  • vh / vw: Relative to viewport height/width
  • auto: Automatically calculated by the browser
  • min-width / max-width: Set minimum or maximum limits for element width

Example: Setting Fixed and Relative Sizes


Shorthand and Defaults

  • By default, most block-level elements expand to width: 100% of their parent container.
  • The height grows to fit the content unless explicitly set.

Best Practices

  • Avoid using fixed px height for elements with dynamic content.
  • Use responsive units (%, vh, vw) to support different screen sizes.
  • Combine min- and max- properties to restrict scaling.
  • Use box-sizing: border-box to include padding and borders within the total width and height.

Key Takeaways

  • width and height define element size on the page.
  • Use relative units for responsive design and better scalability.
  • auto allows content to determine its own dimensions.
  • Use min-width and max-width to control resize boundaries.
  • Combine box-sizing and percentage-based sizing for fluid layouts.