在下面的代码片段中,我有 5 个名为a
到e
的单元格。a
和b
应并排,并尽可能高,宽度固定。c
应该在它们下方,尽可能缩小其高度并匹配a
和b
的总宽度。d
和e
应该在右侧,顶部堆叠有d
,采用所有可用的宽度,e
具有固定的高度,并让d
占据尽可能多的高度。
我不希望c
和e
的高度完全相关。因此,我将d
和e
放在嵌套网格中(出色地命名为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
的计算。相反,您可以使用1fr
和auto
的组合
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>