Layout
CSS Flexbox
Creating Flexible Layouts with Flexbox
CSS flexbox creates flexible layouts with display: flex and flex-wrap.
Introduction to CSS Flexbox
CSS Flexbox, or the Flexible Box Layout, is a powerful layout module designed to provide a more efficient way to align and distribute space among items in a container, even when their size is unknown or dynamic. Flexbox is particularly useful for creating flexible and responsive web designs.
Basic Flexbox Properties
To start using Flexbox, you need to define a flex container by setting the display
property to flex
or inline-flex
. Once a flex container is defined, several properties become available to control the layout:
- flex-direction: Defines the direction flex items are placed in the flex container.
- flex-wrap: Specifies whether flex items should wrap or not.
- justify-content: Aligns flex items along the main axis.
- align-items: Aligns flex items along the cross axis.
- align-content: Aligns a flex container’s lines within the flex container when there is extra space on the cross axis.
Creating a Simple Flexbox Layout
Let’s create a simple flexbox layout with a few items to demonstrate how these properties work. Consider the following HTML structure:
To apply flexbox to this structure, use the following CSS:
Understanding Flexbox Properties
In the example above:
- The container is set to
display: flex;
, making it a flex container. flex-direction: row;
sets the direction of the flex items from left to right.justify-content: space-around;
evenly distributes the children with space around each item.align-items: center;
vertically centers the items within the flex container.- Each
.flex-item
is givenflex: 1;
to grow and fill the space equally.
Using flex-wrap for Multi-line Flex Containers
The flex-wrap
property allows flex items to wrap onto multiple lines. By default, flex items will try to fit onto one line. However, you can change this using:
With flex-wrap: wrap;
, items will wrap onto multiple lines, from top to bottom.
Layout
- Float
- Flexbox
- Grid
- Multi-Column