Overflow & Box Sizing in CSS
Understanding how content behaves inside containers is key for layout control. Overflow handles what happens when content exceeds the container size, and box-sizing controls how dimensions are calculated.
1. CSS Overflow Property
The overflow property controls what happens when content is too big for its container.
visible– default; content spills out.hidden– content is clipped.scroll– adds scrollbars always.auto– adds scrollbars only when needed.
.container {
width: 300px;
height: 100px;
overflow: auto;
}
2. overflow-x & overflow-y
You can control horizontal and vertical overflow separately:
.box {
overflow-x: scroll;
overflow-y: hidden;
}
3. CSS box-sizing Property
The box-sizing property controls how the total width and height of an element is calculated.
content-box– default. Width/height includes only content (padding and border are added).border-box– includes padding and border in the width/height.
/* Common practice */
* {
box-sizing: border-box;
}
This makes layout sizing predictable and avoids unwanted overflow.
4. Example Comparison
Both elements have width: 200px and padding: 20px:
/* content-box (default) */
.box1 {
width: 200px;
padding: 20px;
box-sizing: content-box; /* Total width = 240px */
}
/* border-box */
.box2 {
width: 200px;
padding: 20px;
box-sizing: border-box; /* Total width = 200px */
}
Conclusion
Use overflow to control how excess content behaves, and box-sizing: border-box for reliable layouts. These two properties are essential for building robust and flexible designs.