Swen Swen - 4 months ago 25
HTML Question

How to apply CSS3 flex styles on descending elements?

I just discovered CSS3's

display: flex;
property and tried to apply it to my website's sticky header, but I ran into a problem.

The goal was to evenly space all links across the full width of the header, but this seems impossible when semantically grouping elements with, for example, a
<nav>
tag.

See jsfiddle example: https://jsfiddle.net/9bua0n7o/

<header>
<div class="logo">
Logo
</div>

<nav class="navigation">
<a href="#">Home</a>
<a href="#">FAQ</a>
<a href="#">Contact</a>
</nav>

<div class="search">
<a href="#">Search</a>
</div>

<div class="login">
<a href="#">Register</a>
<a href="#">Login</a>
</div>

</header>


CSS:

header {
width: 100%;
height: 60px;
line-height: 60px;

display: flex;
flex-flow: row wrap;
justify-content: space-between;

position: fixed;
top: 0;
left: 0;

padding: 0 25px;
box-sizing: border-box;

background: #ccc;
}

Answer

You can do like this.

Here I gave each wrapper (navigation, search, etc.) a flex value matching the amount of children they have.

That basically means that the wrapper will occupy that much of the available space and make the items evenly spread.

Then I set each link to flex: 1 making them take its full space.

header {
  width: 100%;
  height: 60px;
  line-height: 60px;
  display: flex;
  flex-flow: row wrap;
  position: fixed;
  top: 0;
  left: 0;
  padding: 0 25px;
  box-sizing: border-box;
  background: #ccc;
}

header .logo,
header .search {
  flex: 1;
  display: flex;
}

header .navigation {
  flex: 3;
  display: flex;
}

header .login {
  flex: 2;
  display: flex;
}

header .navigation a,
header .search a,
header .login a {
  flex: 1;
}
<header>
  <div class="logo">
    Logo
  </div>

  <nav class="navigation">
    <a href="#">Home</a>
    <a href="#">FAQ</a>
    <a href="#">Contact</a>
  </nav>

  <div class="search">
    <a href="#">Search</a>
  </div>

  <div class="login">
    <a href="#">Register</a>
    <a href="#">Login</a>
  </div>

</header>