Flexbox Centering Patterns
Center elements horizontally and vertically using flexbox with justify-content and align-items properties.
Code
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.center-both {
display: flex;
place-items: center;
min-height: 100vh;
}Flexbox Centering Patterns
Center elements horizontally and vertically using flexbox with justify-content and align-items properties.
Code
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.center-both {
display: flex;
place-items: center;
min-height: 100vh;
}
Explanation
justify-content and align-items centre a flex item on both axes, replacing margin-auto hacks. Expected behavior: with a fixed-height container the child sits centred vertically and horizontally. Caveat: with the default align-items: stretch a child of height auto fills the container, so centring needs a definite main size or align-items: center.
Interactive Tools for This Topic
CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
Report a problem with this exampleOpens a pre-filled issue on GitHub.