css - 使用 4 个方形按钮创建响应式布局

标签 css flexbox css-grid

我想创建这样的布局:

enter image description here

黑色边框表示窗口(或容器)的宽度。 粉色方 block 是简单的 div,然后我将其视为按钮。它们的四个大小始终相同,并且始终是正方形。

单个按钮的最大宽度必须为300px,最小为50px。 当有足够的空间时,所有四个按钮都在同一行,否则最后两个位于新的一行。 按钮可调整大小。重要的是它们永远不会小于 50px 并且总是正方形。

我该怎么办?我试过像这样使用 Flexbox:https://codepen.io/anon/pen/NVpzYe

但是显然不行。然后我不知道如何设置合适的高度。

.container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.firstChildren {
  width: 50%;
  border: 1px solid black;
  display: flex;
  height: 50px;
  minWidth: 50px;
}

.secondChildren {
  width: 50%;
  border: 1px solid black;
  height: 50px;
}
<div class="container">
  <div class="firstChildren">
    <div class="secondChildren" />
    <div class="secondChildren" />
  </div>
  <div class="firstChildren">
    <div class="secondChildren" />
    <div class="secondChildren" />
  </div>
</div>

最佳答案

保持与嵌套 flexbox 相同的标记:

  • firstChildren 使用 flex: 1 1 50% 以便它们在行中共享相等的空间,

  • secondChildren 元素上设置 flex: 1 以拉伸(stretch)到可用空间,

  • secondChildren上设置min-width: 50px作为最小宽度要求,

现在给方框添加一些边距,并在一个伪元素上使用padding-top: 100% 使方框变成正方形(请注意 300px max-width 框的限制应用于 firstChild 元素调整此边距) - 尝试更改窗口大小并检查以下代码段:

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.firstChildren {
  flex: 1 1 50%;
  display: flex;
  max-width: 640px; /* max-width = 300px + 4 x 10px margin */
}

.secondChildren {
  flex: 1;
  border: 1px solid black;
  min-width: 50px; /* minimum width */
  margin: 10px;
}

.secondChildren:after { /* create squares */
  content: '';
  display: inline-block;
  vertical-align: top;
  padding-top: 100%;
}
<div class="container">
  <div class="firstChildren">
    <div class="secondChildren"></div>
    <div class="secondChildren"></div>
  </div>
  <div class="firstChildren">
    <div class="secondChildren"></div>
    <div class="secondChildren"></div>
  </div>
</div>

关于css - 使用 4 个方形按钮创建响应式布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162972/

相关文章:

html - 在 flex 行中使用 `nowrap` 时,避免将最后一个元素推出屏幕

html - 我如何在 flex - css 中实现下面的布局

html - 我们可以为单个 div 元素分别设置两个类属性吗?

html - Btn 没有得到颜色

jquery - 使用 flex css 使用 jquery 打印时如何修复未对齐的 html div

css - Flexbox - 第一列全高

html - 列何时收缩到其最大值以下?

css - flex 元素可以包装在具有动态高度的容器中吗?

html - 在我的 CSS 中,网格属性无法正常运行

css - @import 的 SASS/SCSS 自定义 css 表