CSS

Centering Wrapped Flex Items on Each Line

Discover how to horizontally center groups of wrapped Flexbox items on individual lines, perfect for tag clouds or category lists, ensuring a balanced aesthetic.

.wrapper {
  text-align: center; /* This is key for centering the flex container itself */
  max-width: 800px; /* Optional: Constrain width for better centering effect */
  margin: 20px auto;
  border: 1px solid #ddd;
  padding: 15px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center; /* This centers items if there's only one line */
  margin: 0; /* Remove default block margins if any */
  padding: 0; /* Remove default block padding if any */
}

.tag {
  background-color: #007bff;
  color: white;
  padding: 8px 15px;
  margin: 5px; /* Spacing between tags */
  border-radius: 20px;
  font-size: 0.9em;
  white-space: nowrap; /* Prevent tags from breaking */
}

<!-- HTML for context -->
<div class="wrapper">
  <div class="tag-container">
    <span class="tag">CSS Grid</span>
    <span class="tag">Flexbox Layout</span>
    <span class="tag">Responsive Design</span>
    <span class="tag">Web Development</span>
    <span class="tag">Front-end</span>
    <span class="tag">UI/UX</span>
    <span class="tag">HTML5</span>
    <span class="tag">JavaScript ES6+</span>
    <span class="tag">Accessibility</span>
    <span class="tag">Performance</span>
    <span class="tag">Design Systems</span>
    <span class="tag">Animations</span>
    <span class="tag">Vue.js</span>
    <span class="tag">React.js</span>
    <span class="tag">Angular</span>
    <span class="tag">SASS/SCSS</span>
    <span class="tag">CSS Variables</span>
  </div>
</div>
How it works: This snippet demonstrates how to center a collection of wrapped Flexbox items (like tags or chips) on each line. The trick involves wrapping the `tag-container` (which is `display: flex; flex-wrap: wrap; justify-content: center;`) in another block-level element, `.wrapper`, which has `text-align: center;`. This `text-align: center` on the wrapper will center the *flex container itself* if it doesn't take up the full width, effectively centering each line of wrapped items. `justify-content: center` within the flex container ensures items are centered if they don't wrap, or if a line has leftover space.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs