首页 > 解决方案 > 如何在带有伸缩功能的 flexbox 盒子的每一侧放置 4 个“托盘”?

问题描述

有一个主 div (#root),我需要 4 个内部 div,每个 div 都在一侧完全拉伸(运行代码片段以查看)。

现在我在这里:

html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  text-align: center;
}

#root {
  background-color: blue;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 100%;
}

.tray {
  box-sizing: border-box;
  background-color: red;
  border: thin solid black;
}

.tray-top {
  height: 48px;
  width: 100%;
}

.tray-bottom {
  height: 48px;
  width: 100%;
  align-self: flex-end;
}

.tray-left {
  width: 48px;
}

.tray-right {
  width: 48px;
}
<div id="root">
    <div class="tray tray-top">top</div>
    <div class="tray tray-left">left</div>
    <div class="tray tray-right">right</div>
    <div class="tray tray-bottom">bottom</div>
</div>

现在我想在left和之间right完全伸展。topbottom

请注意,所有托盘都有固定宽度(左、右)或固定高度(顶部、底部)。

我会避免将更多的 div 嵌套到现有的中。

Flexbox 不是必须的,但与其他可能性相比,我发现它很容易且面向未来。

标签: htmlcss

解决方案


CSS-Grid 可以做到这一点:

html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  text-align: center;
}

#root {
  background-color: blue;
  display: grid;
  grid-template-columns: auto 1fr auto;
  grid-template-rows: auto 1fr auto;
  height: 100%;
}

.tray {
  box-sizing: border-box;
  background-color: red;
  border: thin solid black;
}

.tray-top {
  height: 48px;
  grid-column: 1 / -1;
}

.tray-bottom {
  height: 48px;
  grid-column: 1 / -1;
}

.tray-left {
  width: 48px;
}

.tray-right {
  width: 48px;
  grid-column:3;
}
<div id="root">
    <div class="tray tray-top">top</div>
    <div class="tray tray-left">left</div>
    <div class="tray tray-right">right</div>
    <div class="tray tray-bottom">bottom</div>
</div>


推荐阅读