CSS网格的动态高度

时间:2019-08-19 15:57:26

标签: html css css-grid

我有一列3行,所有行都有动态高度。我要的是第一行具有最小高度,第二行占据可用空间,第三行也具有最小高度。

这可以实现,问题是我不希望中间行将第三行向下推。所以基本上,我希望第二行占用所有空间并滚动。

在我的示例之后,当我添加一些 li 元素时,就会出现问题。

* {
  box-sizing: border-box;
}

body {
  overflow-y: hidden;
  height: 100vh;
}

.grid {
  display: grid;
  grid-template-rows: min-content 1fr min-content;
  height: 100%
}

ul {
  list-style: none;
  overflow-y: auto;
  height: 70%;
}

li {
  margin: 5px;
  background-color: red;
}

.s-1 {
  background-color: green;
  min-height: 100px;
}

.s-3 {
  background-color: blue;
  min-height: 100px;
}
<section class="grid">
  <div class="s-1">Section 1</div>

  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>

    </ul>
  </div>

  <div class="s-3">Section 3</div>
</section>

When I have the "limit" of li elements

enter image description here

2 个答案:

答案 0 :(得分:0)

.row1 {
  height: 50px;
  width: 100%;
  background: red;
  position: fixed;
  top: 0px;
  left: 0px;
  z-index: 2
}
.row2 {
  height: 100vh;
  background: green;
  position: relative;
  z-index: 1;
}
.row3 {
  height: 50px;
  background: orange;
  position: fixed;
  bottom: 0px;
  left: 0px;
  z-index: 2;
  width: 100%;
}
<div class="row1"></div>
<div class="row2">
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
fsdfsdfsdfsdf <br/>
</div>
<div class="row3"></div>

也许这就是您想要的?

答案 1 :(得分:0)

使用网格-grid-template-rows: 100px calc(100% - 200px) 100px;

使用calc时,我会设置所需的高度,即页面的100%减去顶部和底部。

使用代码笔:(https://codepen.io/omergal/pen/dybpOJr) 在这里我们看不到滚动,因为它在顶部和底部之间

* {
  box-sizing: border-box;
}

body {
  overflow-y: hidden;
  height: 100vh;
  margin: 0;
}

.grid {
  display: grid;
  grid-template-rows: 100px calc(100% - 200px) 100px;
  height: 100%;
}

ul {
  list-style: none;
  overflow-y: auto;
  height: 100%;
  margin:0;
  padding:0;
}

li {
  margin: 5px;
  background-color: red;
}

.s-1 {
  background-color: green;
  height: 100%;
}

.s-3 {
  background-color: blue;
  height: 100%;
}
<section class="grid">
  <div class="s-1">Section 1</div>

  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>

    </ul>
  </div>

  <div class="s-3">Section 3</div>
</section>