问题
In a flexbox I can specify flex-grow:1 on a child to say it should take up the remaining space.
html, body {
height: 100%
}
<div style="display:flex;flex-direction:column;height:100%">
<div style="background-color:yellow;height:50px"></div>
<div style="background-color:red;flex-grow:1"></div>
</div>
Is it possible to do the same thing with css grid? i.e. to specify against a child item that it should use remaining space without defining it explicitly using grid-template-rows?
html, body {
height: 100%
}
<div style="display:grid;grid-template-columns:auto;height:100%">
<div style="background-color:yellow;height:50px"></div>
<!-- what to use instead of flex-grow:1? -->
<div style="background-color:red;flex-grow:1;"></div>
</div>
The real scenario relates to a grid containing a runtime defined number of columns, and a runtime defined set of children some of which may be display:none.
回答1:
You could specify the row height with grid-template-rows: min-content auto;
, which minimizes the first row and stretches the second.
html,
body {
height: 100%
}
<div style="display:grid;grid-template-columns:auto;height:100%;grid-template-rows: min-content auto;">
<div style="background-color:yellow;height:50px"></div>
<div style="background-color:red;"></div>
</div>
回答2:
Use grid-template-rows:
<html style="height: 100%">
<body style="height: 100%">
<div style="display:grid;grid-template-columns:auto;grid-template-rows: 50px auto; height:100%">
<div style="background-color:yellow"></div>
<div style="background-color:red"></div>
</div>
</body>
</html>
Note: the html
and body
need their heights set to 100%
because the grid doesn't automatically grow downwards like flex does.
来源:https://stackoverflow.com/questions/50337909/make-grid-item-use-remaining-space-like-flex-item-with-flex-grow-1