CSS Height & Width

Control the size of elements and build clean, responsive layouts.

What are Height and Width in CSS?

CSS height and width properties are used to define how tall and how wide an element should be. These properties are essential for designing layouts, cards, images, sections, and components.

  • Control element size
  • Create consistent layouts
  • Improve responsive design
  • Prevent layout breaking

Real-Life Example: Width is like the length of a table, height is like how tall it stands.

CSS Width Property

The width property defines the horizontal size of an element.

Basic Width Example


.box {
    width: 300px;
    background-color: #2563eb;
    color: white;
    padding: 20px;
}

                

This box will always be 300px wide, regardless of screen size.

CSS Height Property

The height property defines the vertical size of an element.

Basic Height Example


.box {
    height: 200px;
    background-color: #1e40af;
}

                

Important: Height works properly only when the parent element has a defined height.

CSS Units for Height & Width

  • px – Fixed size
  • % – Relative to parent
  • vw – Viewport width
  • vh – Viewport height
  • auto – Default size

Viewport Units Example


.hero {
    width: 100vw;
    height: 100vh;
}

                

Min & Max Width / Height

These properties help maintain responsiveness while controlling limits.

Min & Max Example


.card {
    min-width: 250px;
    max-width: 400px;
    min-height: 200px;
}

                

Use Case: Perfect for cards that resize but never become too small or too large.

Height & Width for Images

Always use responsive sizing for images to avoid distortion.

Responsive Image


img {
    max-width: 100%;
    height: auto;
}

                

This keeps images responsive across all devices.

Box Sizing and Size Calculation

By default, padding and border add extra size to elements.

Box Sizing Fix


* {
    box-sizing: border-box;
}

                

Pro Tip: Always use border-box for predictable layouts.

Height & Width in Responsive Design

  • Avoid fixed heights when possible
  • Use percentage or auto height
  • Combine with Flexbox or Grid
  • Test on multiple devices

Golden Rule: Let content decide height, you decide width.

Best Practices for CSS Height & Width

  • Prefer flexible units over fixed ones
  • Use min/max properties
  • Avoid fixed height for text content
  • Always think responsiveness first

Final Tip: Good sizing makes layouts stable, bad sizing breaks designs.