首页 > 解决方案 > 包装时有没有办法改变物品的顺序?

问题描述

我正在尝试创建一个网站的一部分,有 3 个部分(我们称它们为 A、B、C),其中 A 和 B 彼此相邻(对齐以接触容器的相对侧),它们下方是 C ,但是当 A 和 B 在容器中不能并排放置时,B 会包裹在 C 下方而不是 A 和 C 之间。

A、B、C都有伸缩组件,容器可以被其他元素调整大小,所以它们的大小都是未知的。这意味着使用@media 是不可能的。

预期结果:
当 A 和 B 并排放置时: 当它们不匹配时: 这可以通过 flexbox 或 grid 实现吗? 据我所知:
当 A 和 B 并排时

当他们不



<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>flexbox black magic</title>
</head>
<body>
    <div style="width:50%; border:4px solid blue; margin:8px; display: flex; justify-content: space-between; flex-wrap: wrap;">
        <div style="width: 100px; height: 60px; border: 4px solid red; margin:8px;">a</div>
        <div style="width: 70px; height: 30px; border: 4px solid green; margin:8px;">b</div>
        <div style="width: 100%">
            <div style="width: 100%; max-width: 240px; height: 100px; border: 4px solid orange; margin:8px;">c</div>
        </div>
    </div>
</body>
</html>

但这不仅会以错误的顺序包装元素,还会使 C 伸出容器外。

标签: htmlcssflexbox

解决方案


这是一个使用浮动的想法,是的。调整蓝色容器的大小并查看结果:

.box {
  width: 50%;
  border: 4px solid blue;
  margin: 8px;
  text-align: justify;
  font-size:0; /* this will make sure the pseudo element won't have any size */
  overflow: auto;
  resize: horizontal;
}
.box > * {
  font-size:initial; /* we reset the font for child element */
  margin:8px;
  box-sizing:border-box;
}
/* the below is used with text-align:justify to have the correct alignment on wrap */
.box::before {
  content:"";
  display:inline-block;
}
.box::after {
  content:"";
  display:inline-block;
  width:100%;
}
/**/
.a {
  max-width: 100px;
  width: calc(100% - 16px);
  height: 60px;
  float:left; /* we float a */
}

.b {
  width: 70px;
  height: 30px;
  display: inline-block;
}

.c {
  height: 100px;
  width: calc(100% - 16px);
  max-width: 240px;
  float:left; /* and we float c */
  clear:left; /* don't forget this to make "c" always below "a" */
}
<div class="box">
  <div class="a" style="border: 4px solid red;">a</div>
  <div class="c" style="border: 4px solid orange;">c</div>
  <div class="b" style="border: 4px solid green;">b</div>
</div>


推荐阅读