当嵌套网格更改大小时,CSS 网格会更改轨道大小



在下面的代码片段中,我有 5 个名为ae的单元格。ab应并排,并尽可能高,宽度固定。c应该在它们下方,尽可能缩小其高度并匹配ab的总宽度。de应该在右侧,顶部堆叠有d,采用所有可用的宽度,e具有固定的高度,并让d占据尽可能多的高度。

我不希望ce的高度完全相关。因此,我将de放在嵌套网格中(出色地命名为de(。我希望当我将e的高度设置为某个值时,它应该变成那个高度,d应该根据需要缩小或增长,其他一切都应该保持不变。但是,当我改变e的高度时,c也会改变它的高度。

为什么我的嵌套网格会影响它的父级,我该如何防止它?

这是片段,以防万一。您可以通过调整输入的值来更改e的高度。

let e = document.getElementById('e')
let heightInput = document.querySelector('#controls input')
heightInput.addEventListener('input', function() {
	e.style.height = heightInput.value + 'px'
})
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#controls {
height: 25px;
padding: 5px;
}
#grid {
background: orange;

width: 100%;
height: calc(100% - 35px);

display: grid;
grid-template-columns: min-content min-content auto;
grid-template-rows: auto min-content;
grid-template-areas:
'a b de'
'c c de';
}
#a {
background: red;

grid-area: a;
width: 30px;
}
#b {
background: blue;

grid-area: b;
width: 30px;
}
#c {
background: green;

grid-area: c;
}
#de {
background: purple;

grid-area: de;
display: grid;
grid-template-rows: auto min-content;
grid-template-areas:
'd'
'e';
}
#d {
background: grey;

grid-area: d;
}
#e {
background: yellow;

grid-area: e;
height: 30px;
}
<body>
<div id="controls">
Set height of e in px <input type="number" value="30" />
</div>
<div id="grid">
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
<div id="de">
<div id="d">d</div>
<div id="e">e</div>
</div>
</div>
</body>

实际上我没有准确的解释,但这是由于min-content的计算。相反,您可以使用1frauto的组合

let e = document.getElementById('e')
let heightInput = document.querySelector('#controls input')
heightInput.addEventListener('input', function() {
	e.style.height = heightInput.value + 'px'
})
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#controls {
height: 25px;
padding: 5px;
}
#grid {
background: orange;

width: 100%;
height: calc(100% - 35px);

display: grid;
grid-template-columns: min-content min-content auto;
grid-template-rows: 1fr auto; /* updated this */
grid-template-areas:
'a b de'
'c c de';
}
#a {
background: red;

grid-area: a;
width: 30px;
}
#b {
background: blue;

grid-area: b;
width: 30px;
}
#c {
background: green;

grid-area: c;
}
#de {
background: purple;

grid-area: de;
display: grid;
grid-template-rows: 1fr auto;  /* updated this too but not mandatory */
grid-template-areas:
'd'
'e';
}
#d {
background: grey;

grid-area: d;
}
#e {
background: yellow;

grid-area: e;
height: 30px;
}
<body>
<div id="controls">
Set height of e in px <input type="number" value="30" />
</div>
<div id="grid">
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
<div id="de">
<div id="d">d</div>
<div id="e">e</div>
</div>
</div>
</body>

最新更新