Course contentsShow
← Web Development
Lesson 141 of 2,9823. CSS FundamentalsFree lesson

Width and Height Fundamentals

Control element dimensions and understand how box-sizing affects calculated size.

Width and Height Fundamentals

You'll learn how to control the exact dimensions of HTML elements using CSS width and height properties.

What Are Width and Height?

Every element on a webpage can be given specific dimensions. The width property controls how wide an element is, and the height property controls how tall it is. Think of it like setting the size of a picture frame—you decide how much space the frame takes up on your wall.

Basic Syntax

.box {
  width: 300px;
  height: 200px;
}

This creates an element that's 300 pixels wide and 200 pixels tall.

Common Units

You can specify dimensions using:

  • Pixels (px): Fixed size (e.g., width: 250px)
  • Percentages (%): Relative to the parent element (e.g., width: 50%)
  • Auto: Let the browser calculate the size (the default)

How Box-Sizing Affects Size

Remember from the previous lesson that box-sizing changes what your width and height actually measure:

  • box-sizing: content-box (default): Your width/height only applies to the content area. Padding and border get added to it.
  • box-sizing: border-box: Your width/height includes content, padding, and border. This makes sizing more predictable.
.predictable-box {
  width: 300px;
  padding: 20px;
  border: 5px solid black;
  box-sizing: border-box; /* Total width stays exactly 300px */
}

Auto Values

If you don't set a width, block elements default to width: auto, which means they'll expand to fill their container. Height defaults to auto as well, expanding to fit the content inside.

Key Takeaway: Width and height control element dimensions, and box-sizing: border-box makes those dimensions include padding and border, giving you more predictable sizing control.