Most Common Examples of CSS Flex (with Source Code)
CSS flexbox is a layout model that makes it easier to align and distribute space among items in a container, even when the size of the items is unknown or dynamic.
Some popular examples of using CSS flexbox include:
- Creating a "flexible" (automatically stretchable) row, column or grid of items, where the items are distributed evenly across the width of the parent container, and can wrap onto multiple rows as needed.
- Vertically aligning an item within a container, regardless of the size of the item or the container.
- Creating a sticky footer that stays at the bottom of the page, even if the page content is not long enough to push it down.
Here is an example of using CSS flexbox to create a flexible grid of items:
.container { display: flex; flex-wrap: wrap; } .item { flex: 1 1 auto; }
This will create a container with the flex display type, and the flex-wrap property set to wrap. This allows the items to wrap onto multiple rows as needed. The flex property on the items is set to 1 1 auto, which means that the items will take up equal amounts of space within the container, but will shrink or grow as needed to fit the available space.
How to quickly align a Flex item vertically within parent container?
Here is an example of using CSS flexbox to vertically align an item within a container:
.container { display: flex; align-items: center; }
This will create a container with the flex display type, and the align-items property set to center. This will vertically align the items within the container, so that they are centered along the vertical axis.
How to create a sticky footer in Flex?
Here is an example of using CSS flexbox to create a sticky footer:
.container { display: flex; flex-direction: column; min-height: 100vh; } .main-content { flex: 1; } .footer { position: fixed; bottom: 0; left: 0; right: 0; }
So what's going on here? This example is explained below:
This code above will create a container with the flex display type, and the flex-direction property set to column.
flex-direction set to column will make a flex container that arranges its items in vertical column order. The min-height property is set to 100vh, which means that the container will always take up at least the full height of the viewport.
The main-content element is given the flex property set to 1, which means that it will take up all the available space within the container.
The footer element is given the position property set to fixed, which means that it will remain in a fixed position at the bottom of the page, even if the page is scrolled.
The bottom, left, and right properties are set to 0, which means that the footer will be positioned at the bottom edge of the container, and will stretch to fill the full width of the container.
I hope this helps someone!