html - 为什么子 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>
解决方案
原因
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>
推荐阅读
- regex - 提取excel单元格中复杂分隔符之间的文本
- javascript - 在javascript中添加输入时未定义的输出
- powerbi - Power BI 将 DAX 应用于聚合后经过的时间 hh:mm:ss 的列
- python-3.x - 在网站模块中重用表单、树、看板视图
- driverless-ai - 我正在尝试在本地 Ubuntu 机器上启动 driverlessai
- php - Laravel 5.4 不一致无响应且日志中无错误
- javascript - AgGrid 自定义时间过滤器
- groovy - Groovy Jmeter 在列表中收集 XML 的元素
- android - Android 内核 Zimage 解压
- jenkins - Jenkins 因“PKIX 路径构建”错误而失败