CSS – Working with Width, Height, Max-Width and Overflow

When building a website layout, controlling the size of your elements is essential. You want images, boxes, and sections to fit neatly, whether viewed on a phone or a desktop.

In this tutorial, we will learn:

  • How to set width and height
  • Why max-width is important for responsive design
  • How to handle overflow when content doesn’t fit

CSS Width and Height

You can control the size of elements using CSS width and height properties.

Syntax:

selector {
  width: value;
  height: value;
}

Example:

.box {
  width: 300px;     /* sets box width to 300 pixels */
  height: 150px;    /* sets box height to 150 pixels */
  background-color: lightblue;
}

Tips:
🔷 If you don’t set a height, the element adjusts to its content.
🔷 And if you don’t set the width, the block elements take 100% of the parent width by default, while inline/inline-block elements shrink to fit content.

CSS Max-Width

max-width allows an element to scale down on small screens, but not grow beyond a limit.

Syntax:

selector {
  max-width: value;
}

Example:

img {
  max-width: 100%;    /* keeps image within container */
  height: auto;       /* maintains aspect ratio */
}

Tip:
🔷 If you only use width: 100%, an image might stretch beyond its natural size. CSS max-width property prevents that.

CSS Overflow

When content doesn’t fit inside a box (like too much text), the CSS overflow property helps manage it.

Syntax:

selector {
  overflow: value;
}

Values for overflow:

  • visible: Default value and content spills out if it’s larger than the size of the element
  • hidden: Clips extra content
  • scroll: Always adds scrollbars
  • auto: Adds scrollbars only if needed

Example:

.container {
  width: 200px;
  height: 100px;
  overflow: auto;
  border: 1px solid black;
}
<div class="container">
  This is a long text that might not fit inside the box unless scrolling is enabled.
</div>

Tips:
If overflow property is not applied to an element with a fixed width and height, then:
🔷 The content can overflow (spill out) of the box visibly, beyond the element’s boundaries.
🔷 The element does not clip, hide, or add scrollbars automatically.
🔷 The overflow is visible by default.

Where is it really useful? – To create scrollable areas for chat boxes, sidebars, or fixed-height widgets.

Summary

PropertyWhat It Does
widthSets width of an element
heightSets height of an element
max-widthPrevents element from exceeding max-width
overflowHandles overflow content (scroll, hide, etc.)

Practice Challenge

Create a div with:

  • Width: 250px
  • Height: 120px
  • Background: #f0f0f0
  • Border: 1px solid gray
  • Overflow: scroll

Fill it with long content and observe how scrolling works.

Sharing Is Caring...