CSS
Distributing Navigation Items with Flexbox `justify-content`
Master how to evenly distribute navigation links or other UI elements within a horizontal container using Flexbox `justify-content` for clean and adaptable spacing.
.navbar {
display: flex; /* Enable Flexbox for horizontal layout */
list-style: none; /* Remove default list styling */
margin: 0;
padding: 0;
background-color: #28a745; /* Example background */
align-items: center; /* Vertically center items */
height: 60px; /* Example height */
}
/* Distribute items with space between them */
.navbar-space-between {
justify-content: space-between;
}
/* Distribute items with space around them */
.navbar-space-around {
justify-content: space-around;
}
/* Distribute items with space evenly */
.navbar-space-evenly {
justify-content: space-evenly;
}
/* Items aligned to start, with gap */
.navbar-start-gap {
justify-content: flex-start;
gap: 1.5rem; /* Modern way to add spacing between items */
}
.navbar li a {
color: white;
text-decoration: none;
padding: 0 1rem;
font-weight: bold;
}
.navbar li a:hover {
background-color: rgba(255, 255, 255, 0.2);
}
How it works: This snippet illustrates how `justify-content` in Flexbox is used to distribute space between items along the main axis (horizontally, by default). `space-between` places the first and last items at the edges and evenly distributes remaining space. `space-around` places equal space on both sides of each item. `space-evenly` ensures equal space *between* items and *at the ends* of the container. `flex-start` aligns items to the beginning, and `gap` provides consistent spacing.