When parent is display: flex;
, is there a way to force it's children to stretch itself to 100% of the parent's width and height, without accessing the children's props?
i've found align-items: stretch;
for vertical stretching, but can't find something for the horizontal.
"I've found align-items: stretch; for vertical stretching, but can't find something for the horizontal"
I guess you're searching for justify-content
property, but it doesn't have stretch
rule, it only can accept the following rules: justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
But
You can specify flex-grow: 1
for child element and it will fill all available space of the parent.
Here is the example (I have added paddings to parent element just for example, so you can see the difference between parent and child):
.wrapper {
display: flex;
width: 80%;
height: 300px;
background-color: orangered;
padding: 8px;
}
.item {
flex-grow: 1;
background-color: forestgreen;
}
<div class="wrapper">
<div class="item"></div>
<div>
is there a way to force it's children to stretch itself to 100% of the parent's width and height, without accessing the children's props?
No, as for an i.e. flex row item (the default), its default width is auto
, which make it depend/size by its content, and for it to stretch horizontal (fill the remaining space), it needs flex-grow: 1
.
The same goes for flex column item, where the flex-grow: 1
will make it fill the parent's height.
i've found
align-items: stretch;
for vertical stretching, but can't find something for the horizontal
When it comes to align-items
and its default stretch
, it affect the cross axis, and will for i.e a flex row item, stretch it to fill its parent's height, and for a flex column item it is the other way around, where it fill its parent's width.
There is no property for the main axis that does the same, as that is what the flex
property is for, here as shorthand flex: <flex-grow> <flex-shrink> <flex-basis>
, and since one might want different behavior for different items, it is set on the flex item (what you call the child)
Here is a flex row samples using flex-grow: 1
.parent {
display: flex;
height: 200px;
background: red;
}
.child {
flex-grow: 1;
background: blue
}
<div class='parent'>
<div class='child'></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With