iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Height/Width

Width and height set the size of an element. Pair them with max-width and min-width for responsive layouts.

Sizing in practice

EXAMPLE
/* Fixed pixel size */
.box {
  width: 320px;
  height: 200px;
}

/* Percentage of parent */
.col {
  width: 50%;
  height: 100%;
}

/* Viewport units - relative to the browser window */
.hero {
  height: 100vh;      /* full viewport height */
  width:  100vw;      /* full viewport width  */
}

/* The modern dvh / svh / lvh handle mobile address bars */
.hero {
  height: 100dvh;     /* dynamic - updates as browser UI shows/hides */
}

/* Intrinsic sizing keywords */
.fits {
  width: fit-content;    /* shrinks to content, up to max-content */
  height: max-content;
}

/* min / max for responsive constraints */
.card {
  width: 100%;
  max-width: 32rem;      /* never larger than 512px */
  min-height: 12rem;
}

/* clamp() - the modern fluid sizing */
.fluid {
  width: clamp(20rem, 50%, 60rem);
  /* min 320px, ideal 50% of parent, max 960px */
  font-size: clamp(1rem, 2vw + 0.5rem, 1.5rem);
}

/* aspect-ratio replaces hacks like padding-bottom: 56.25% */
.video {
  width: 100%;
  aspect-ratio: 16 / 9;
}

/* Block-level elements default to width: auto = fill parent */
/* Inline elements ignore width and height - set display: inline-block or block first */

/* Box-sizing matters - border-box includes padding + border in the width */
* { box-sizing: border-box; }

Why it matters

Set width with constraints (max-width, clamp) instead of fixed pixels. Use aspect-ratio for media boxes - it removes the padding-bottom hack. dvh/svh/lvh fix the 100vh-on-mobile bug that has haunted designers for a decade.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Height/Width</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Cap this container at 1100px while letting it shrink on small screens.

.container { width: 100%; : 1100px; margin: 0 auto; }

Test yourself

Q1. Which property keeps an element from shrinking smaller than 240px?
Q2. What does `max-width: 100%; height: auto` on an image do?
Q3. In `.container { width: 100%; max-width: 1100px; }` the element will…

Discussion

Loading…