All examples

Layouts & positioning > Flexbox
Flexbox example: gaps

With flexbox you can lay out items in a container along one axis. You can also specify how available space is used.

In this demo we set gaps betwen the items.

Example code

							<div class="flex-container">
  <div class="flex-item">A</div>
  <div class="flex-item">B</div>
  <div class="flex-item">C</div>
  <div class="flex-item">D</div>
</div>

<style>
.flex-container {
  display: flex; 
	align-items: flex-start;
	gap: 1em;
}

/* for demonstration */
@layer for-demo {
	.flex-container {
		background-color: hotpink; 
		min-height: 20em;
		align-items: flex-start;
	}
	.flex-item {
		aspect-ratio: 1 / 1;
		border-radius: .25em;
		background-color: #fff;
		border: 1px solid #ccc;
		padding: 2em;
	}
	.flex-item:nth-child(2) {
		padding: 3em 1em;
	}
	.flex-item:nth-child(3) {
		padding: 2.5em 1.5em;
	}
}
</style>
						

Preview

Gap between lines

If there's multiple lines of flex items, the gap between the lines will be the gap that was between the items.

You can change that and specifically control what the gap should be between lines by adding a second parameter to the gap property.

.flex-container {
  gap: 1em 2em; /* first is between lines, second between items */
}

Example code

							<div class="flex-container">
	<div class="flex-item">A</div>
	<div class="flex-item">B</div>
	<div class="flex-item">C</div>
	<div class="flex-item">D</div>
	<div class="flex-item">E</div>
	<div class="flex-item">F</div>
	<div class="flex-item">G</div>
	<div class="flex-item">H</div>
	<div class="flex-item">I</div>
	<div class="flex-item">J</div>
	<div class="flex-item">K</div>
	<div class="flex-item">L</div>
</div>

<style>
.flex-container {
	display: flex; 
	align-items: flex-start;
	gap: 2em .5em;
}

/* for demonstration */
@layer for-demo {
	.flex-container {
		background-color: hotpink; 
		min-height: 20em;
		align-items: flex-start;
		align-content: flex-start;
		flex-wrap: wrap;
	}
	.flex-item {
		aspect-ratio: 1 / 1;
		border-radius: .25em;
		background-color: #fff;
		border: 1px solid #ccc;
		padding: 2em;
	}
	.flex-item:nth-child(2) {
		padding: 3em 1em;
	}
	.flex-item:nth-child(3) {
		padding: 2.5em 1.5em;
	}
}
</style>
						

Preview