When using a flex container, elements will try to fit into it without line breaks. In this case, the elements inside the container behave more or less like inline elements, only occupying the space they need.
So, what happens if there isn't enough room inside the container? According to the container's logic, elements must be placed in a single line, unless otherwise specified. Therefore, the elements inside will simply start to leave the boundaries of the container, staying on the same line. It may be a little unclear, but this behavior often helps when creating layouts, it's useful when designing sliders, for example.
I've added padding to the elements inside the container, so you can see its actual width. This behavior, while helpful, isn't usually expected. How do you wrap elements in that case? To do this, we can use the flex-wrap
property, which tells the container to move child elements when there isn't enough space.
The flex-wrap
property can take one of three values:
nowrap
. Standard flex container behavior. Elements are not wrapped and are placed in one line, even if there isn't enough spacewrap
. Wraps elements inside the container if there isn't enough space
wrap-reverse
. Same aswrap
, except it puts them in reverse order. In this case, the line with the values1
and2
will be lower, unlike how it is with a simplewrap
Using flex-wrap
is a great choice when creating adaptive websites. Although this one property can't solve all problems at once, using it on your site's layout will help with automatically moving elements to a new line when there isn't enough space on mobile devices.
Docs
- flex-wrap
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.