Search code examples
cssflexboxcss-grid

Why is the display flex and display grid positions different?


Ok, so when you display flex, the default is a row which is the main axis from left to right then the column is the cross axis which is from top to bottom, but when you display grid the row is usually from top to bottom and column from left to right. Why are the directions different, i'm confused which is row and column, is it not supposed to be the same directions for both the flex and grid?


Solution

  • For flexbox the direction is by default row

    The flex-direction property specifies how flex items are placed in the flex container, by setting the direction of the flex container’s main axis. This determines the direction in which flex items are laid out.

    Initial: row ref

    For CSS grid the flow is also row but the placement algorithm is different:

    Initial: row

    The auto-placement algorithm places items by filling each row in turn, adding new rows as necessary.

    The trick is in the adding new rows. By default, we have no row and no column but only one grid line in each axis.

    If these properties don’t define any explicit tracks the explicit grid still contains one grid line in each axis. ref

    So for each item the browser will create a new row and you will have your top to bottom layout.

    If you change the flow to column you will have the opposite behavior

    column

    The auto-placement algorithm places items by filling each column in turn, adding new columns as necessary.


    Both flexbox and CSS grid behave the same but the difference is that in CSS grid you need to define columns, if you don't do the browser will assume one column and placing the element from left to right then from top to bottom will be seen as a top to bottom only. Flexbox place items considering the free space and there is no column concept. Same logic for the column layout.