Center elements horizontally and vertically with flexbox
Quick Answer
Set `display: flex; justify-content: center; align-items: center;` on the parent to centre any child both horizontally and vertically.
1.center {
2 display: flex;
3 justify-content: center;
4 align-items: center;
5}Flexbox centering with justify-content and align-items set to center is the modern standard for centering elements in CSS. It replaces older hacks like negative margins, absolute positioning, and table-cell tricks, and works reliably for both fixed and dynamic content sizes.
`justify-content` aligns items along the main axis (horizontal by default). `align-items` aligns items along the cross axis (vertical by default). Both are needed for true two-dimensional centering.
This free css code snippet for flexbox centering is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement flexbox centering quickly and correctly.
All snippets in the Snippetly library follow css best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses css.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.