Wrapping items are positioned horizontally and center aligned. How would you control the vertical and horizontal spacing?
In this example, we'd like to have 16px horizontal space between items and 8px vertical space.
Here is a possible solution:
/* Solution */
.flex-wrapper {
padding-top: 1px;
}
.flex-wrapper:before {
content: "";
display: block;
margin-top: -9px;
}
.flex {
display: flex;
flex-wrap: wrap;
margin-left: -16px;
justify-content: center;
}
.flex-item {
padding-left: 16px;
padding-top: 8px;
}
/* For demo purposes, not related to solution. */
body {
margin: 50px;
}
.container {
width: 600px;
outline: 1px solid black;
}
button {
width: 100px;
height: 40px;
background: none;
border: 4px solid red;
font-size: 16px;
}
<div class="container">
<div class="flex-wrapper">
<div class="flex">
<div class="flex-item">
<button>1</button>
</div>
<div class="flex-item">
<button>2</button>
</div>
<div class="flex-item">
<button>3</button>
</div>
<div class="flex-item">
<button>4</button>
</div>
<div class="flex-item">
<button>5</button>
</div>
<div class="flex-item">
<button>6</button>
</div>
<div class="flex-item">
<button>7</button>
</div>
<div class="flex-item">
<button>8</button>
</div>
<div class="flex-item">
<button>9</button>
</div>
</div>
</div>
</div>
This solution feels somewhat hacky, especially the .flex-wrapper
part.
Is there a better way?
Notes:
- Items can have various widths.
- I'm looking for a solution that works regardless of whether the items wrap or not. Items can also span across many lines, not just 2 lines like in this example.
- At the time of writing this question, browsers don't have a great support for
gap
inFlex
.
This question shows how to horizontally center align the items, but it doesn't demonstrate how to control the vertical and horizontal space between the items.