An Interactive Guide to CSS Flex Box
📣 Sponsor
In the past, making HTML elements appear next to each other was a tricky proposition. It usually relied on floats, often resulting in some strange behaviours. Today, we have flex box, which is widely accepted as the standard way to do this. Flex box lets us align content in columns or rows, while automatically adjusting its size based on how we set it up. Below, you can view the complete guide to CSS flex box, along with a generator to let you generate the layout style you want for your container elements.
Create your flex box
align-items:
justify-content:
flex-direction:
For items..
flex-grow:
With flex box, the container element has to have display: flex;
. We can also do inline-flex
, for flex boxes inline with the text.
.container {
display: flex;
align-items: normal;
flex-direction: row;
justify-content: flex-start;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
.item {
flex-grow: 0;
}
Properties for Containers
For your reference, here are the individual properties and the effects they have on a flex box configuration. For all of these examples, except flex-wrap itself, we use flex-wrap: wrap;
.
justify-content
This justifies content along the flex-direction
axis.
.container {
justify-content: start;
}
align-items
This aligns the content along the axis perpendicular to the flex-direction
axis for a single row of items.
.container {
align-items: normal
}
flex-direction
This sets then main axis of the flex, whether that is vertical (column) or horizontal (row).
.container {
flex-direction: normal
}
align-content
This sets the position for all rows in a much larger box.
.container {
align-content: flex-start
}
flex-wrap
This sets the position for all rows in a much larger box.
.container {
flex-wrap: nowrap;
}
Properties for Items
Although you can affect entire collections of items with flex box, you can also call out individual items and apply styles to them in particular. Below, the examples show you how to do that.
order
When applied to an item, it gives it an order relevant to other items around it. An order of 9999 will go to the end of the flow direction. Think of this like z-index
, but for flex box.
.item {
order: 0;
}
flex-grow
Dictates the alignment of a particular item along the perpendicular axis to flow-direction
.
.item {
flex-grow: 1;
}
align-self
Dictates the alignment of a particular item along the perpendicular axis to flow-direction
.
.item {
align-self: flex-start;
}
More Tips and Tricks for CSS
- CSS Transformations
- Multi colored text in CSS
- CSS Transitions
- Making a CSS Only Minecraft Chicken
- How to make a child element appear behind its parent in CSS
- A first look at CSS When and Else Statements
- CSS Pseudo Elements
- Sticky Positioning with CSS
- CSS Only Masonry Layouts with Grid
- CSS Layers Tutorial: Real CSS Encapsulation