首页 > 解决方案 > Flexbox 列布局:1 向左,2 堆叠在右侧

问题描述

我正在尝试使用 flexbox 实现以下响应式网格布局,但我无法在没有固定高度的情况下获得正确的“桌面”版本。我希望#1 位于左侧,#2 和 #3 彼此堆叠在右侧(#1 不必与右侧 col 具有相同的高度)

在此处输入图像描述

HTML(简体)

<div class="wrapper">
  <div class="inner">
    <div class="col1"></div>
    <div class="col2"></div>
    <div class="col3"></div>
  </div>
</div>

CSS(简体)

.wrapper {
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #c4c4c4
}

.col1, .col2, .col3 {
  background: #fe4c4c;
  position: relative;
  margin: 10px;
  padding: 5px;
  color: #FFF;
  font-weight: bold;
  font-size: 40px;
  font-family: sans-serif;

  min-height: 100px;

  &:after {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.col1 {
  &:after {
    content: '1';
  }

  width: 100px;
}

.col2 {
  &:after {
    content: '2';
  }

  width: calc(100% - (100px + 60px))
}

.col3 {
  &:after {
    content: '3';
  }

  width: calc(100% - 30px);
}

.inner {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

@media only screen and (min-width: 768px) {  
  .inner {
    flex-direction: column;
  }

  .col1 {
    width: 300px;
  }

  .col2 {
    width: auto;
  } 

  .col3 {
    width: auto;
  }
}

jsFiddle https://jsfiddle.net/pcwudrmc/28053/

我四处寻找类似的问题,但找不到没有固定高度的答案。

提前致谢!

标签: htmlcssflexbox

解决方案


使用 CSS 网格的解决方案:

https://codepen.io/seanstopnik/pen/bd511c728bb79d02d11ae04edbfe9a33

* {
  box-sizing: border-box;
}

.wrapper {
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #c4c4c4;
  padding: 10px;
}

.col1,
.col2,
.col3 {
  background: #fe4c4c;
  position: relative;
  color: #fff;
  font: {
    family: sans-serif;
    size: 40px;
    weight: 700;
  }
  min-height: 100px;

  &:after {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.col1:after {
  content: '1';
}

.col2:after {
  content: '2';
}

.col3:after {
  content: '3';
}


// Inner
.inner {
  display: grid;
  grid: {
    template-columns: 100px auto;
    template-rows: 100px;
    gap: 10px 10px;
  }

  @media (min-width: 768px) {
    grid-template-columns: 300px auto;
  }
}

.col1 {

  @media (min-width: 768px) {
    grid: {
      column: 1 / span 1;
      row: 1 / span 2;
    }
  }
}

.col3 {
  grid: {
    column: 1 / span 2;
    row: 2 / span 2;
  }

  @media (min-width: 768px) {
    grid: {
      column: auto;
      row: auto;
    }
  }
}

推荐阅读