Flexbox is a layout model that allows you to design complex layouts with a single container element and its children. It's a powerful tool that makes it easier to create responsive designs and align elements in a predictable way.
To use Flexbox, you need to define a display: flex;
property on the parent container. This will turn the container into a flex container and allow you to use flex properties to control the layout of its children.
<!-- HTML --><div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div>
/* CSS */.container { display: flex; }
There are several properties you can use to control the layout of the flex container:
flex-direction
: defines the direction of the main axisjustify-content
: aligns items along the main axisalign-items
: aligns items along the cross axisflex-wrap
: controls how items wrapalign-content
: aligns items when there is extra space in the cross axisgap
: defines the space between itemsHere's a demo showing a typical flexbox use case of a navigation bar:
<!-- HTML --> <nav class="navbar"> <svg>...</svg> <a href="#">Home</a> <a href="#">About</a> <a href="#">Services</a> <a href="#">Contact</a> </nav> /* CSS */ .navbar { display: flex; justify-content: flex-start; align-items: center; gap: 0.25rem; }
There are also properties you can use to control the layout of the flex items:
flex-grow
: how much an item will grow relative to the other itemsflex-shrink
: how much an item will shrink relative to the other itemsflex-basis
: the initial size of an itemorder
: the order of the item in the flex containeralign-self
: allows an item to override the align-items
value for its containerHere's an example using the order
property to move the second item to the beginning:
<!-- HTML --> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div> /* CSS */ .container { display: flex; } .item:nth-of-type(2) { order: -1; }
Here's an example using the flex-grow
property to make the first item grow to fill the available space:
.item:first-of-type { flex-grow: 1; }
As a shorthand, you can use the flex
property to set the flex-grow
, flex-shrink
, and flex-basis
values at once. Some examples:
flex: 1;
will make an item grow to fill the available space.flex: 0 1 200px;
will make an item not grow, shrink to fit, and have an initial size of 200px..item { flex: 1; }
Here are a few different examples of navigation bars using flexbox. Use your browser's dev tools to inspect the elements and see how they work.