Oct 19, 2016Last modified May 16, 2025
Notes on grid and flexbox layout in css
Flexbox layout
- Flexbox is a one dimentional layout model. You can control the alignments of the items along one axis.
- The flexbox layout is directionally agnostic. You can use it to create layouts that work in both left-to-right and right-to-left languages.
- Flexbox enables you to control layout at two levels - the flex container and the flex items.
- The flex container is the element that contains the flex items.
- To turn any block element into a flex container, you set the display property to flex.
- You can decide how you want to render the contents of the container ie. either horizontally or vertically, using the flex-directon prioperty.
- You can also decide how you want to wrap the items if they don't fit in a single row or column, using the flex-wrap property.
- You can also decide how you want to align the items within the container, using the justify-content & align-items property.
- Here's sample example :
- The flex items are the elements that are contained within the flex container.
- You can control the size of the items using the flex-grow, flex-shrink, and flex-basis properties.
- You can also control the order of the items using the order property.
- You can also control the alignment of the items within the container, using the align-self property.
- Here's sample example :
- flex:1 is a shorthand property which translates to flex-grow:1 (expand to take the extra space) , flex-shrink:1 (shrink to fit in space) and flex-basis:0% (initial size of the item).
- If you have multiple flex items with flex: 1, they will share the available space equally.
- If one item has flex: 2 and another has flex: 1, the first will take twice as much space as the second.
Implementing Holy-Grail layout with flexbox
Grid layout
- Grid layout is a two dimentional layout model. You can control the alignments of the items along both the axis.
- Key Grid Properties:
For the Parent (grid container):
- display: grid - Defines a grid container
- grid-template-columns - Defines column sizes
- grid-template-rows - Defines row sizes
- grid-template-areas - Defines named grid areas
- grid-gap - Spacing between grid cells
- justify-items - Aligns items horizontally within their cell
- align-items - Aligns items vertically within their cell
For the Children (grid items):
- grid-column - Specifies which column(s) the item spans
- grid-row - Specifies which row(s) the item spans
- grid-area - Places an item in a named grid area
Implementing Holy-Grail layout with grid
When to Use Flexbox:
- One-dimensional layouts (single row or column)
- When you need to distribute space among items
- When the exact positioning isn't as important
- For smaller component layouts
When to Use Grid:
- Two-dimensional layouts (rows and columns)
- When you need precise control over placement
- For complex layouts with overlapping elements
- When designing the overall page structure