【发布时间】:2021-03-21 21:37:12
【问题描述】:
我为整个网站制定了一个非常标准的布局——页眉/页脚、两个侧块和中心的主要内容。让我们把页脚/页眉放在一边,它们并不是很有趣。我想要实现的是两件事:
- 将红色块放置在青色和绿色之间,在手机上进行自适应布局。
- 同时保持桌面布局灵活。也就是说,我不想在蓝色和红色块之间有额外的空间(当青色块有很多内容时),我也不希望在青色和绿色块之间有额外的空间(当蓝色块有很多内容时)
首先我是用 flexbox 做的,但是第 1 点在 Flex 中是不可能的。现在我将其重写为使用 Grid 并遇到了 #2 的问题。
问题 - 如何使每列中的网格元素在高度方面相互“独立”(当然,保持确定性行为)?
这是示意图布局(顶部 - 桌面,底部 - 移动):
这里是CodePen example(单击洋红色块以检查它的行为方式和问题所在)
var testing = true;
function startTime() {
if (testing) {
document.getElementById('info').innerHTML = "<br>LongLongContent<br>LongLongContent<br><br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>";
document.getElementById('content').innerHTML = "Short content (logs block should start just after me)";
} else {
document.getElementById('content').innerHTML = "<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>LongLongContent<br>";
document.getElementById('info').innerHTML = "Short content (photos block should start just after me)";
}
testing = !testing;
}
.grid-container {
display: grid;
grid-template-columns: 210px 1fr 200px;
grid-template-rows: repeat(4, auto);
gap: 0px 0px;
grid-template-areas: "header header header"
"info content sidebar"
"photos logs sidebar"
"footer footer footer";
}
.grid-container>* {
border: 1px solid red;
}
.header {
grid-area: header;
}
.info {
grid-area: info;
background-color: blue;
color: white;
}
.photos {
grid-area: photos;
background-color: red;
}
.footer {
grid-area: footer;
}
.sidebar {
grid-area: sidebar;
background-color: magenta;
}
.content {
grid-area: content;
background-color: cyan;
}
.logs {
grid-area: logs;
background-color: green;
}
<header class="grid-container">
<header class="header">Header</header>
<div class="info" id="info">Info<br>Info<br>Info<br>Info<br>Info<br>Info<br><br>Info<br></div>
<div class="photos">Photos<br>Photos<br>Photos<br>Photos<br>Photos<br></div>
<div class="content" id="content">content<br>asdasd<br><br><br>[I'm some random empty space =(]</div>
<div class="logs">logs</div>
<div class="sidebar" id="sidebar" onclick="startTime()">Click me to toggle between different sizes of content</div>
<footer class="footer">Footer</footer>
</div>
【问题讨论】: