Vertically Centering a Div in CSS: Techniques and Examples
Balancing visual elements on a webpage can be a critical aspect of web design. One common task is to vertically center a `div` or any other content block within a container. This can be achieved using various methods, each with its own advantages. For modern web design, the use of CSS Flexbox is a popular and efficient way to handle vertical centering. Let's explore different techniques and provide examples for each method.CSS Flexbox Method
Flexbox is a powerful layout tool that simplifies the task of arranging elements in a row or column. Here's how you can vertically center a `div` using Flexbox:Flexbox for Body Level
```css body { display: flex; align-items: center; height: 100vh; } ``` ```html This is centered vertically ``` Note the use of `align-items: center;` to vertically center the content and `height: 100vh;` to ensure the `body` container fills the entire viewport. Additionally, adding `justify-content: center;` to center the content horizontally is useful.Flexbox for Outer and Inner Classes
Another way to achieve vertical centering is by using relative and absolute positioning inside a Flexbox container. Here's how you can do it: ```css .outer { display: table; position: absolute; height: 100vh; width: 100vw; } .middle { display: table-cell; vertical-align: middle; } .inner { margin-left: auto; margin-right: auto; width: 50%; } ``` ```htmlThe Content
Once upon a midnight dreary...
``` In this approach, the `.outer` class acts as a container that occupies the full viewport, and the `.middle` class centers the inner content both vertically and horizontally. The `.inner` class ensures the content is centered horizontally within the middle section.