【发布时间】:2021-08-23 06:36:57
【问题描述】:
这是我想要实现的布局:
Mobile: Desktop:
+-------------------+ +-----------+---------------------+
| C | | C | |
+-------------------+ +-----------+ |
| | | P | |
| | +-----------+ |
| V | | | V |
| | | | |
| | | | |
+-------------------+ | | |
| P | | | |
+-------------------+ +-----------+---------------------+
100% 300px 100% - 300px
所以如果屏幕足够宽(min-width: 960px),元素V会从另外两个之间拉出,并向右移动。
请注意,所有元素(包括外部容器)都没有固定的已知高度。它们都必须自动调整大小以适合其内容。
移动版对 DOM 来说也是一个明智的顺序,所以让我们使用这个 HTML:
<div class="outer">
<div class="C"></div>
<div class="V"></div>
<div class="P"></div>
</div>
我首先尝试用flexbox实现桌面布局:
@media screen and (min-width: 960px) {
.outer {
display: flex;
flex-direction: column;
}
.C { order: 1; width: 300px; }
.V { order: 3; }
.P { order: 2; width: 300px; }
}
这会处理重新排序,但在 P 和 V 之间似乎有 no way to force a wrap 没有设置固定高度。所以元素保持堆叠在一起。
我还尝试使用浮点数将V 拉出:
@media screen and (min-width: 960px) {
.C { width: 300px; }
.V { width: calc(100% - 300px); margin-left: 300px; float: right; }
.P { width: 300px; }
}
但它最终会低于C。为了解决这个问题,我必须更改 DOM 顺序,出于可访问性的原因,我不想这样做。
我也可以用绝对定位拉出V:
@media screen and (min-width: 960px) {
.outer { position: relative; }
.C { width: 300px; }
.V { width: calc(100% - 300px); right: 0; top: 0; }
.P { width: 300px; }
}
问题在于V 不再影响outer div 的高度,并开始与outer 下面的内容重叠。
最后我考虑了 CSS grid,但它会降低浏览器的兼容性。
有没有一种方法可以在不使用丑陋的 hack 的情况下创建这种布局?
【问题讨论】:
标签: html css flexbox css-float css-grid