0

On a high level, the goal is to center a block of elements that span multiple lines, where each line is left aligned.

Specifically, there is a container and several elements inside of it. Depending on the width of the screen, more elements can fit into one line. The container should take the width of the longest possible line that fits inside the container, but not more. This would then allow me to center the block of elements by centering the container. Ideally, the solution would not involve JavaScript.

What I have tried:

  • In the example below, I fixed the container maximum width, showing the unwanted additional empty space on the right inside of the container. As a result, the block of elements is not centered on the page but too far to the left.
  • I also attempted to center the elements inside the container. This way, the block of elements becomes centered on the page. However, the lines of course don't start at the same vertical line anymore as they should.
  • The reason I cannot fix the container width in advance is that on smaller screens, its content should break into more shorter lines to still fit onto the screen.

body {
  background: #aaa;
}

.container {
  max-width: 14em;   /* Should be width of longest content line */
  margin: 0 auto;    /* Center the container on the page */
  text-align: left;  /* Left align elements inside the container */
  background: #666;
}

.container > div {
  display: inline-block;  /* Allow multiple elements on one line */
  margin: .5em;
  background: #fff;
}
<div class="container">
  <div style="width: 3em; height: 2em;"></div>
  <div style="width: 4em; height: 2em;"></div>
  <div style="width: 4em; height: 1em;"></div>
  <div style="width: 4em; height: 1em;"></div>
  <div style="width: 3em; height: 2em;"></div>
  <div style="width: 2em; height: 1em;"></div>
  <div style="width: 3em; height: 2em;"></div>
  <div style="width: 4em; height: 1em;"></div>
<div>

The unnecessary space I'm trying to get rid of is marked in red:

unnecessary space

danijar
  • 32,406
  • 45
  • 166
  • 297
  • 1
    short answer: you cannot ... – Temani Afif Mar 18 '20 at 23:47
  • For elements of equal width you can, using `display: inline-grid; grid-template-columns: repeat(auto-fit, );` as pointed out in the question this is was duplicate of. – danijar Mar 19 '20 at 00:00
  • yes but you don't have equal width item. For equal width item you need to simply define the number of item per row and its done or use CSS grid – Temani Afif Mar 19 '20 at 00:01
  • Yes. I wanted to avoid specifying the number of items per row so they can adjust to different screen sizes. However, I needed to wrap all elements in boxes of equal size for it to work, as you pointed out. – danijar Mar 19 '20 at 18:57

0 Answers0