CSS, HTML

Responsive Header Layout with Flexbox

Create a flexible and responsive header with a logo, navigation, and action items using CSS Flexbox for dynamic positioning and stacking on different screen sizes.

<header class="header">
  <div class="header__logo">Logo</div>
  <nav class="header__nav">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Services</a>
  </nav>
  <div class="header__actions">
    <button>Login</button>
    <button>Sign Up</button>
  </div>
</header>

.header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #f0f0f0;
  gap: 1rem; /* Use gap for spacing between items */
}

.header__logo {
  font-weight: bold;
  font-size: 1.5rem;
  flex-shrink: 0; /* Prevent logo from shrinking */
}

.header__nav {
  display: flex;
  flex-grow: 1; /* Allow nav to take available space */
  justify-content: center; /* Center nav items when space allows */
  gap: 1rem;
  flex-wrap: wrap; /* Allow nav items to wrap */
}

.header__nav a {
  text-decoration: none;
  color: #333;
  padding: 0.5rem 1rem;
}

.header__actions {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0; /* Prevent actions from shrinking */
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch; /* Stretch items to full width */
  }
  .header__nav,
  .header__actions {
    width: 100%;
    justify-content: center; /* Center nav/actions when stacked */
  }
  .header__logo {
    margin-bottom: 1rem; /* Add space below logo */
    text-align: center;
  }
}
How it works: This snippet demonstrates how to build a flexible and responsive header using CSS Flexbox. It uses `display: flex`, `justify-content: space-between`, and `align-items: center` for initial desktop layout. `flex-wrap: wrap` allows items to move to the next line on smaller screens. Media queries adjust `flex-direction` to `column` and `align-items` to `stretch` for mobile, ensuring a clean stacked layout. The `gap` property simplifies spacing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs