CSS Width and Height

Width and height properties control element dimensions. They can use absolute units, percentages, or special keywords for flexible layouts.

Setting Dimensions

width and height set the size of an element's content area (by default).

Values can be lengths (px, em, rem), percentages (of parent), or auto.

auto (default) lets content determine size.

Block elements default to 100% width, inline elements to auto.

/* Fixed dimensions */\n.box {\n  width: 300px;\n  height: 200px;\n}\n\n/* Percentage (of parent) */\n.half {\n  width: 50%;\n  height: 100%;\n}\n\n/* Auto (default) */\n.auto {\n  width: auto; /* Fill available width for blocks */\n  height: auto; /* Fit content */\n}\n\n/* Viewport units */\n.fullscreen {\n  width: 100vw; /* 100% of viewport width */\n  height: 100vh; /* 100% of viewport height */\n}

Min and Max Dimensions

min-width and min-height set minimum sizes.

max-width and max-height set maximum sizes.

These override width/height when constraints are violated.

Useful for responsive design and preventing content overflow.

/* Flexible width with constraints */\n.container {\n  width: 100%;\n  max-width: 1200px;\n  min-width: 320px;\n  margin: 0 auto;\n}\n\n/* Responsive images */\nimg {\n  max-width: 100%;\n  height: auto;\n}\n\n/* Flexible height */\n.sidebar {\n  min-height: 300px;\n  max-height: 800px;\n  overflow-y: auto;\n}