Take 2 columns in 2-columns layout but not when 1-column layout in CSS grid without @media

前端 未结 3 1669
面向向阳花
面向向阳花 2021-01-25 09:09

The desired layout for wide screens:

The desired layout for narrow screens:

Initial CSS:

.La         


        
3条回答
  •  悲哀的现实
    2021-01-25 09:22

    Finally I think I could handle your problem, but by using flex instead of grid. It is pretty tricky.

    The main element is a class called wrapper, which has display: flex;. You can insert your "grid items" there, now called wrapper-container.

    I need this helper class to recreate the grid-gap property. Now I am using padding instead. Note that padding works a bit ditterent to grid-gap so I had to divide your gap by 2.

    Each wrapper-container has a wrapper-container__item child, which contains your content. When you inspect these elements, you will notice, that they have at least a width of 240px which is caused by their min-width property.

    When you want an element to span over two "columns" add the class wrapper-container__stretched to the wrapper-container. It is applying width: 100% so that the element will be fullsized. Elements which do not have the class, has flex: 1, so they will stay next to each other (just like a 2-column grid).

    Feel free to ask when there are any ambiguities.

    Codepen: Responsive grid without media queries using flex-box

    .wrapper{
      position: relative;
      width: 100%;
      background: #dedede;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .wrapper-container{
      position: relative;
      padding: 12px 20px;
    }
    
    .wrapper-container:not(.wrapper-container__stretched){
      flex: 1;
    }
    
    .wrapper-container.wrapper-container__stretched{
      width: 100% !important;
    }
    
    .wrapper-container__item{
      position: relative;
      min-width: 240px;
      min-height: 64px;
      width: 100%;
    }
    
    
    .red{
      background: #e53935;
    }
    
    .green{
      background: #388e3c;
    }
    Item 1
    Item 2
    Item 3
    Item 4
    Item 5

提交回复
热议问题