【问题标题】:Flex masonry effect not wrapping properly弯曲砌体效果未正确包裹
【发布时间】:2019-02-11 22:30:04
【问题描述】:

我尝试使用 flex 实现以下布局,但似乎无法实现:

* {
  box-sizing: border-box;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
  float: left;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

如果我尝试使用 flex-direction 行,它会将最后两个框包裹在第一个左框下方

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

如果我使用 flex 方向列,我会更近,但必须设置一个高度,这意味着我失去响应能力

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:400px;
  width:100%;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

有没有办法在不固定高度或改变html结构的情况下使用flex来实现这种布局?

【问题讨论】:

  • 如果这四个框都是同一个父级的子级,我认为你至少需要引入另一个分组元素......这里的问题是你不是只在一个维度上工作,你这样做没有行 cols,你有两个 - 这意味着这将是 CSS 网格开始的一项工作。
  • 嗯,我也是这么想的。正在考虑使用网格,可能只是我需要移动到它的推动力

标签: css flexbox


【解决方案1】:

使用 flexbox,您可以考虑一些 hack 来近似这一点。一个技巧是有两行(保持行方向)并在第一个元素上使用负边距以使其与第二行重叠:

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.box {
  outline: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 25%;
  margin-bottom:-25%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
.box:nth-child(3) {
  margin-left:auto;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 2016-11-12
    • 2013-12-21
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多