html - 如何将元素包装在 flexbox 中以适应较小的屏幕?

标签 html css flexbox

我正在尝试为不同的调整大小创建布局。我需要在此处获得这些图像中的结果:

flexbox result

我有这个代码:

.container {
  position: relative;
  display: flex;
  align-items: stretch;
}
.item {
  background-color: black;
  box-sizing: border-box;
  padding: 20px;
  flex: 2;
  color: #fff;
}
.item:nth-child(2) {
  background-color: grey;
  flex: 1
}
.item:nth-child(3) {
  background-color: green;
  flex: 0.5;
}
@media screen and (max-width: 990px) {
  .container {
    height: auto;
    display: table;
  }
  .item:nth-child(2) {
    float: left;
  }
  .item:nth-child(3) {
    float: right;
  }
}
<section class="container">
  <div class="item">
    <h2>title1</h2>
    <hr>You'll notice that even though this column has far more content in it, instead of the other columns ending early, they size themselves to meet the end of this column vertically.</div>
  <div class="item">
    <h2>title2</h2>
    <hr>Normally, the only way to achieve this would be either a hack, or to set all boxes to min-height.
  </div>
  <div class="item">
    <h2>title3</h2>
    <hr>This is a column with not much content.
  </div>
</section>

这里有一个codepen https://codepen.io/darudev/pen/pyBrzL

问题出在 990 像素调整大小 View 中,我找不到创建与“模型”相同 View 的解决方案。

有没有人可以帮助我或给我一些建议?

谢谢。

最佳答案

您的代码中不需要 table 和 float 属性。

@media screen and (max-width: 990px) {
  .container {
    height: auto;
    display: table;
  }
  .item:nth-child(2) {
    float: left;
  }
  .item:nth-child(3) {
    float: right;
  }
}

整个布局都可以用flexbox做。

解决方案如下:当屏幕调整到小于 990 像素时,允许 flex 元素换行并为第一个元素提供 100% 宽度,这会强制后续元素到下一行。

.container {
  display: flex;
}

.item {
  background-color: black;
  box-sizing: border-box;
  padding: 20px;
  flex: 2;
  color: #fff;
}

.item:nth-child(2) {
  background-color: grey;
  flex: 1;
}

.item:nth-child(3) {
  background-color: green;
  flex: 0.5;
}

@media screen and (max-width:990px) {
  .container { flex-wrap: wrap;  }
  .item:first-child { flex-basis: 100%; }
}
<section class="container">
  <div class="item">
    <h2>title1</h2>
    <hr>You'll notice that even though this column has far more content in it, 
         instead of the other columns ending early, they size themselves to meet the end
         of this column vertically.</div>
  <div class="item">
    <h2>title2</h2>
    <hr>Normally, the only way to achieve this would be either a hack, or to set
        all boxes to min-height.</div>
  <div class="item">
    <h2>title3</h2>
    <hr>This is a column with not much content.
  </div>
</section>

revised codepen

关于html - 如何将元素包装在 flexbox 中以适应较小的屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218224/

相关文章:

html - 是否有关于 HTML 资源包的建议?

javascript - 为什么<a>标签用%2520替换空格?如何解决问题?

html - 掩码属性在 Firefox 中不起作用

css - 页面顶部的页脚渲染——Rails

html - 使用 CSS 进行立方体旋转

css - Flexbox 在不改变子元素宽度的情况下限制每行的元素

css - 堆叠在小型设备上的 Flexbox

html - 幻灯片 Angular 不起作用

html - 在固定布局网站中出现网站宽度错误

html - 将元素底部对齐,同时在 flexbox 中保持拉伸(stretch)