CSS Flexible Box Layout

CSS flexbox is a layout model in CSS that allows to arrange and align items within a container. The layout can adapt to different screen sizes and devices. The model works by defining a container element and one or more child elements that will be arranged within that container. Then it can be specified how the child elements should be laid out, including their direction, order, alignment, and size.

The CSS flexbox layout is one-dimensional, it operates along single axis so is best to use to arrange rows or columns.

The default flexbox layout

The Flexbox Layout

Syntax:

The CSS rule for a flex container – the parent of flex items:

.flex-container {
    display: flex | inline-flex;
}

CSS properties used with a flex parent:

Property Initial value  
flex-direction row Use to set items on desirable axis and direction (normal or reversed).
flex-wrap nowrap Use to force items onto one line or to wrap onto multiple line.
justify-content flex-start Use to align items on the main axis.
align-items stretch Use to align items on the cross axis.
align-content stretch Use to set the distribution of space between and around items along a flexbox’s cross axis.

The shorthand

The flex-flow CSS property is a shorthand property for: flex-direction and flex-wrap

flex-flow: flex-direction flex-wrap;

The CSS properties used with flex items

Property Initial value
order 0
align-self auto
flex-grow 0
flex-shrink 1
flex-basis auto

The shorthand

flex property is a shorthand for three sizing properties: flex-grow, flex-shrink, flex-base.

flex: flex-grow flex-shrink flex-base;

For example flex: 3 is equivalent:

flex-grow: 3;
flex-shrink: 1;
flex-basis: 0%;

The flex shorthand property, when set to flex: 3, only specifies the value of flex-grow, while flex-shrink takes its default value of 1. Additionally, if flex-basis is not explicitly defined elsewhere in the code, it will be set to 0%.

See the Pen flexbox flex by majadc (@majadc) on CodePen.

Examples

.flex-container {
  display: flex;
  flex-wrap: wrap;
}

1. Defaults values for flex properties

flex-grow: 0;
flex-shrink: 1;
flex-basis: auto;
1
2
3
4

2. Default values for flex properties with a declared width property.

width: 250px;
1
2
3
4

3. Setting value for flex-basis

flex: 0 1 250px;
width: 100px;

However, if flex-basis is declared, the value of width is omitted.

1
2
3
4

4. Changing default values of flex-grow and flex-shrink

flex: 1 0 250px;
1
2
3
4

5. Allowing flex items growing and shrinking

flex: 1 1 250px;
1
2
3
4

Related

Resource

Posted in CSS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.