Box Model: CSS3 Box-Sizing & Calc()
Master CSS Box Model and Modern Layout Techniques
Core Concepts Covered
CSS3 Box-Sizing
Learn how to switch between traditional and modern box models for more predictable layouts.
Calc() Function
Master CSS calculations with mixed units like percentages and pixels for precise positioning.
Responsive Design
Build layouts that adapt seamlessly across different screen sizes and devices.
Exercise Setup Process
Open Project Files
Open the Box Sizing folder in your code editor and locate index.html
Preview in Browser
Open index.html in your browser to see the initial two-column layout
Test Responsiveness
Resize the browser window to observe percentage-based column scaling
Box Model Comparison
| Feature | Traditional Box Model | New Box Model |
|---|---|---|
| Size Calculation | Size + Padding + Border | Specified Size Only |
| CSS Property | box-sizing: content-box | box-sizing: border-box |
| Padding Effect | Increases total size | Stays within specified size |
| Layout Predictability | Requires calculations | More intuitive |
Return to your code editor to implement the modern box model approach.
Add the
box-sizingproperty to switch to the intuitive box model that most developers prefer:.primary,.secondary { float: left; width: 50%; padding: 40px; box-sizing: border-box; }The border-box value fundamentally changes how the browser calculates element dimensions. Now the 50% width represents the total width, with padding calculated internally rather than added externally.
- Save the file and observe the immediate improvement.
- Reload your browser. The columns should now sit properly side-by-side, maintaining their responsive behavior while incorporating the visual spacing we wanted.
- However, you'll notice the center gap between columns appears wider than the outer margins. This occurs because we're applying 40px padding to all sides of both columns, creating an 80px combined gap in the center while maintaining only 40px margins on the outer edges.
- Let's create visual balance by adjusting the inner padding. Return to your code editor.
We'll override the inner padding to create consistent spacing throughout the layout. Add the following specific rules:
.primary { padding-right: 20px; }.secondary { padding-left: 20px; }This approach uses CSS specificity to override the general padding rule for just the inner edges, creating a uniform 40px gap throughout the layout.
- Save the file and reload your browser to see the improved, balanced spacing.
Return to your code editor to continue with the next phase of the exercise.
Key Takeaways
