CSS Layouts
Modern CSS provides powerful tools for creating flexible, responsive layouts. This section covers essential layout techniques that form the foundation of contemporary web design.Core Layout Concepts
The Box Model
Understanding the CSS box model is fundamental to creating reliable layouts. By default, thewidth and height of an element are calculated based on the content property only, meaning padding and border increase the total size.
Using box-sizing: border-box changes this behavior to include padding and border in width and height calculations, making layouts more predictable.
Flexbox Layouts
Flexbox is the preferred method for most modern layouts. It provides powerful alignment capabilities with minimal code. Usingdisplay: flex creates a flex context for direct children.
Key properties:
justify-content- Alignment along the main axisalign-items- Alignment along the cross axisflex-direction- Sets the main axis direction (row or column)flex-wrap- Controls whether items wrap onto multiple linesgap- Spacing between flex items
Grid Layouts
CSS Grid excels at two-dimensional layouts where you need control over both rows and columns. It’s particularly useful for page-level layouts and complex component structures. Key properties:grid-template-columns/grid-template-rows- Define grid structuregap- Spacing between grid itemsgrid-area- Position items in named areasfrunit - Distributes available space proportionally
Common Layout Patterns
Centering Content
Centering content is one of the most common layout tasks. Modern CSS offers several reliable approaches: Flexbox centering (recommended):Sticky Footer
Ensuring the footer stays at the bottom of the page, even with short content, is easily achieved with modern CSS. Using Flexbox:Even Distribution
Distributing child elements evenly within a container is straightforward with Flexbox:Best Practices
- Use Flexbox for one-dimensional layouts (rows or columns)
- Use Grid for two-dimensional layouts (rows and columns)
- Always set
box-sizing: border-boxfor predictable sizing - Prefer logical properties for better internationalization
- Use modern viewport units (
dvh,dvw) with fallbacks - Test layouts at various viewport sizes