使用 Flexbox 重新创建 CSS 网格布局

马克·沃特斯

这是我使用 CSS 网格为以列表格式显示事件的网站创建的简单布局。信息区域包含日期,还有两个区域用于内容和特色图像。使用grid-roworder这可以在相对较少的行中完成。

我正在尝试使用 Flexbox 提高我的技能,并尝试重新创建相同的布局(根据断点对布局进行类似调整)但失败了。如果有人能指出我正确的方向或提供类似的例子,我将不胜感激!

代码在这里:https : //codepen.io/mwaterous/pen/OrPmLL

内马尼亚

我很高兴您已经找到了实现这一目标的方法之一(使用重组的 HTML)。如果出于任何原因,您被无法更改的 HTML 卡住了,这可能是解决方案之一。

免责声明:如果我们在一个父级中有 3 个兄弟 div 并且我们要使用 flexbox,那么主要的挑战(也是真正的问题)是如何实现二维布局(使用 CSS 网格很容易实现)。

css grid 相对于 flexbox 的最大优势在于它允许您在 2 维中操作内容。我使用 flexbox 实现这一点的解决方案需要绝对定位的“帮助”,但它确实有效。我有意将代码的某些部分注释掉以向您展示替代方案,并且我尝试包含一些有用的注释。不幸的是,代码片段不允许使用 scss 代码,因此我会将它与此一起包含在正文中:https ://codepen.io/nemanjaglumac/pen/OrVgLR

// HTML CODE
<section class="container">
  <div class="cell info">.info</div>
  <div class="cell main">.main</div>
  <div class="cell image">.image</div>
</section>

css的一种选择。

// SCSS CODE
// GLOBAL VARIABLES
$main-color: #fff;

*,
*:before,
*:after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  background: linear-gradient(-20deg, #00b09b, #96c93d);
  min-height: 100vh;
  font-family: Ubuntu, sans-serif;
  font-size: 18px;
  text-shadow: 1px 1px 0 #000;
  color: $main-color;
  text-align: center;
}

.cell {
  background-color: rgba($main-color, 0.15);
  border: 1px solid $main-color;
  border-radius: 2px;
  padding: 20px;
  margin: 10px;
  text-align: center;

  &:hover {
    background-color: rgba($main-color, 0.25);
  }
}

@media screen and (min-width: 768px) {
  .container {
    display: flex;
    flex-flow: wrap-reverse; // this has saved us 3 lines of code (flex-direction: row [1], flex-wrap: wrap [2], and then later we would have to set order to -1 on .image [3])
    // flex-direction: row; // [1]
    // flex-wrap: wrap; // [2]
    position: relative;
    height: 300px;
  }

  .info {
    width: 180px;
    position: absolute;
    top: 0;
    bottom: 0;
    // left: 0; 
  }

  .main, 
  .image {
    width: calc(100% - 180px - 4*10px); // we need to count all four margins (2elements x left+right)
    margin-left: auto; // this moves elements all the way to the right. Alternative would be to set justify-content of the .container to flex-end, but then we would need to explicitly set .info's left position to 0 to "keep it in place"
  }

  // .image {
  //   order: -1; [3]
  // }
}

@media screen and (min-width: 1021px) {
  .info {
    position: initial;
  }

  .main,
  .image {
    margin: 10px;
  }

  .main {
    flex: 2;
  }

  .image {
    flex: 1;
    // order: 0; [3]
  }
}

补充阅读:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章