Register to get access to free programming courses with interactive exercises

Wrapping elements in a container CSS: Flexbox fundamentals

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 space
  • wrap. Wraps elements inside the container if there isn't enough space
  • wrap-reverse. Same as wrap, except it puts them in reverse order. In this case, the line with the values 1 and 2 will be lower, unlike how it is with a simple wrap

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.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY