CSS
Flexbox: Efficiently Arrange Wrapping Elements with `flex-wrap` and `gap`
Master CSS Flexbox `flex-wrap` and `gap` to create dynamic, space-efficient layouts for tag lists, button groups, or chips that wrap naturally onto new lines while maintaining consistent spacing between all items, horizontally and vertically.
/* CSS */
.tag-list-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
gap: 10px; /* Provides consistent spacing between items */
border: 1px solid #eee;
padding: 15px;
max-width: 400px; /* Example constraint for wrapping */
}
.tag-item {
background-color: #e0f7fa;
color: #00796b;
padding: 8px 12px;
border-radius: 20px;
font-size: 0.9em;
white-space: nowrap; /* Prevents tag text from breaking */
}
/* HTML Structure (for context):
<div class="tag-list-container">
<span class="tag-item">Flexbox</span>
<span class="tag-item">CSS Grid</span>
<span class="tag-item">Responsive</span>
<span class="tag-item">Web Dev</span>
<span class="tag-item">HTML5</span>
<span class="tag-item">JavaScript</span>
<span class="tag-item">Design</span>
<span class="tag-item">Frontend</span>
</div>
*/
How it works: This snippet demonstrates how to create a flexible, wrapping layout for elements like tags or buttons using Flexbox. By setting `display: flex` and `flex-wrap: wrap`, items will automatically flow onto the next line when the container runs out of space. The `gap` property provides uniform spacing between all flex items, both horizontally and vertically, simplifying layout by eliminating the need for complex margins on individual items, leading to cleaner and more maintainable CSS.