Writing flexbox code for 2-column and 3-column on desktop and mobile (wrap)

后端 未结 2 732
天涯浪人
天涯浪人 2021-02-01 04:29

I\'m having a real hard time figuring out this CSS flexbox solution. Basically there are 2 issues, one with a 2-column and another with a 3-column layout.

2-Column:

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 05:11

    I will assume desktop means screen wider than 600px, mobile less.

    The 2-column layout is very simple:

    body {
      display: flex;   /* Magic begins */
      flex-wrap: wrap; /* Allow multiple lines */
    }
    #left, #right {
      flex: 1 300px;   /* Initial width of 600px/2
                          Grow to fill remaining space */
      min-width: 0;    /* No minimal width */
    }
    

    body {
      display: flex;
      flex-wrap: wrap;
      text-align: center;
      font-weight: bold;
    }
    #left, #right {
      flex: 1 300px;
      min-width: 0;
      background: #f55;
      padding: 15px 0;
    }
    #right {
      background: #57f;
    }
    Left

    The 3-column is only a bit more complex:

    body {
      display: flex;            /* Magic begins */
    }
    #left, #right, #middle {
      min-width: 0;             /* No minimal width */
    }
    #left, #right {
      flex-basis: 200px;        /* Initial width */
    }
    #middle {
      flex: 1;                  /* Take up remaining space */
    }
    @media screen and (max-width: 600px) { /* Mobile */
      body {
        flex-direction: column; /* Column layout */
      }
      #left, #right {
        flex-basis: auto;       /* Unset previous 200px */
      }
      #middle {
        order: 1;               /* Move to the end */
      }
    }
    

    body {
      display: flex;
      text-align: center;
      font-weight: bold;
    }
    #left, #right, #middle {
      min-width: 0;
      padding: 15px 0;
    }
    #left, #right {
      flex-basis: 200px;
      background: #f55;
    }
    #right {
      background: #57f;
    }
    #middle {
      flex: 1;
      background: #5f6;
    }
    @media screen and (max-width: 600px) {
      body {
        flex-direction: column;
      }
      #left, #right {
        flex-basis: auto;
      }
      #middle {
        order: 1;
      }
    }
    Left
    Middle

提交回复
热议问题