6

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.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Or Bachar
  • 1,451
  • 3
  • 15
  • 20

2 Answers2

7

"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>
P.S.
  • 15,970
  • 14
  • 62
  • 86
  • `flex: 1;` is **not** equal to `flex-grow: 1` – Asons Nov 06 '17 at 16:04
  • That describe the _syntax_ for `flex` shorthand and does not say they are equal. The W3C specs. is the [proper docs](https://www.w3.org/TR/css-flexbox-1/#flex-common), and this answer explains it: https://stackoverflow.com/a/35395869/2827823 – Asons Nov 06 '17 at 16:11
5

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>
Asons
  • 84,923
  • 12
  • 110
  • 165