CSS Flexbox and Its Properties
Before we dive in to CSS Flexbox, let us learn about Pre Flexbox
Pre Flexbox: A recap of some properties in CSS which might be related to learning Flexbox.
- We have different positional properties such as ‘absolute’ and ‘relative’ depending on how we want to place our elements in our page.
- Floats, grids, clear fixes to help aid in the positioning.
- Fixed heights for columns (one of the main elements to create flexboxes).
What exactly is a flexbox?
- Flexbox is a CSS display type design to help us craft CSS layouts quite easily.
- Control the position, size and spacing of elements relative to their parents elements and each other.
- They are great for responsive designing.
- It has its own set of properties.
- It defines formatting context, which controls layout.
- It is a parent-child relationship.
Note: Not all browsers support the flexbox properties, so make sure that the browser you are using supports this property.
Basics of Flexbox:
Apply a display type of flexbox to the parent container, this would make all the child elements in it to adjust into the flex type and these would be called the “flex items”. This means they have become more flexible i.e. we can control how much they can shrink and how much they can grow and also the spacing between these elements.
display: flex property:
- The flex container can change the width, height and order of the child elements.
- Items can grow or shrink to fill the available space or to prevent overflow.
- Available space is distributed among other items.
Axes of flexbox:
- The main axis:
A) left to right
B) right to left
C) top to bottom
D) bottom to top
- The cross axis (perpendicular to main axis)
Properties of flexbox:
- display defines a flex container – flex formatting context.
- flex-direction defines the main axis inside the container.
- flex-wrap allows flex items to wrap onto more than one line.
- flex-flow shorthand for flex-direction + flex-wrap.
- justify-content allows items to align along main axis.
- align-content allows items to align along cross axis in a single line.
- align-items aligns multiple lines of items on the cross axis.
- order allows the change of order of items without altering the source order.
- flex-grow allows an item to fill up the available free space.
- flex-shrink allows an item to shrink if there is no enough free space available.
- flex-basis defines the size of an item before space is distributed.
- flex is the shorthand for flex-grow + flex-shrink + flex-basis.
- flex-self has the ability to align one single item within the flex container.
Before applying flex properties:
After applying flex properties:
Yes, only this much code in CSS can make such a huge difference using flex-box.
Benefits of a flexbox:
- Navigation bars and menus
- Grid Layouts
- Bar charts
- Equal height columns