首页 > 解决方案 > 为什么子 div 占用父 div 的 100% 高度并显示:网格

问题描述

我有一个具有显示网格和高度 100% 的 paren div。由于某种原因,即使我没有指定高度为 100%,它里面的所有子 div 现在都具有 100% 的高度。我怎样才能使子 div 具有基于其内容的高度。

.parent {
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  gap: 0;
}

.child {
  width: 100%;
  display: flex;
  background: red;
}
<div class="parent">
  <div class="child">
    <div class="child-1">
      child
    </div>
  </div>
</div>

标签: htmlcss

解决方案


原因

align-items原因是网格容器上CSS 属性的默认值为normal. 这个属性定义了align-self那些没有明确设置的网格单元的行为(垂直对齐)align-self

MDN

normal

这个关键字的效果取决于我们所处的布局模式:

  • 在绝对定位布局中,关键字在替换的绝对定位框上的行为类似于 start,在所有其他绝对定位框上的行为类似于拉伸。
  • 在绝对定位布局的静态位置中,关键字表现为拉伸。
  • 对于 flex 项目,关键字的行为类似于拉伸。
  • 对于网格项,此关键字导致类似于 的行为stretch,除了具有纵横比或固有尺寸的框,其行为类似于start
  • 该属性不适用于块级框和表格单元格。

html, body { height: 100%; margin: 0; color: white; }

.parent {
  background-color: orange;
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  gap: 10px;
}

.child {
  background-color: red;
  width: 100%;
}
<div class="parent">
  <div class="child">
    child 1
  </div>
  <div class="child">
    child 2
  </div>
</div>

解决方案

如果您希望所有网格单元从单元格顶部开始并具有height: auto,只需align-items: start;在您的网格容器上应用:

html, body { height: 100%; margin: 0; color: white; }

.parent {
  background-color: orange;
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  gap: 10px;
  align-items: start;
}

.child {
  background-color: red;
  width: 100%;
}
<div class="parent">
  <div class="child">
    child 1
  </div>
  <div class="child">
    child 2
  </div>
</div>

如果您只希望某些网格单元从单元格顶部开始并具有height: auto,只需align-self: start;在这些网格单元上应用:

html, body { height: 100%; margin: 0; color: white; }

.parent {
  background-color: orange;
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  gap: 10px;
}

.child {
  background-color: red;
  width: 100%;
}

.auto-height {
  align-self: start;
}
<div class="parent">
  <div class="child auto-height">
    child 1
  </div>
  <div class="child">
    child 2
  </div>
</div>


推荐阅读