A flex container helps arrange items in a row or column easily. It makes layouts flexible and neat without complicated code.
Flex container in CSS
selector {
display: flex;
}Use display: flex; on a container to make it a flex container.
All direct children of this container become flex items.
nav element a flex container, so its child links line up in a row by default.nav {
display: flex;
}.container { display: flex; flex-direction: column; }
.box { display: flex; justify-content: center; align-items: center; }
This example creates a flex container with three items. They appear side by side with space between them. On small screens, they stack vertically. The container and items have colors and padding for clarity.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Flex Container Example</title> <style> .flex-container { display: flex; gap: 1rem; background-color: #f0f0f0; padding: 1rem; border: 2px solid #ccc; } .flex-item { background-color: #4caf50; color: white; padding: 1rem 2rem; border-radius: 0.5rem; font-weight: bold; flex: 1; text-align: center; } @media (max-width: 600px) { .flex-container { flex-direction: column; } } </style> </head> <body> <section class="flex-container" aria-label="Example flex container"> <div class="flex-item">Item 1</div> <div class="flex-item">Item 2</div> <div class="flex-item">Item 3</div> </section> </body> </html>
Flex containers only affect their direct children, not nested elements inside those children.
Use browser DevTools to see the flex container and items highlighted and experiment with properties live.
Flexbox works well for one-dimensional layouts (row or column), not complex grids.
Flex container arranges child items in a row or column easily.
Set display: flex; on a container to start using flexbox.
Flexbox helps create responsive and neat layouts with little code.