anoop chandran anoop chandran - 3 months ago 18
CSS Question

Dashboard header using CSS Flexbox

I want to create something like this using CSS Flexbox:

enter image description here

I usually achieve this using floats and lots of positioning tweaks, adding margins, padding, percentage values on top, bottom, left and right of the elements to adjust it to a certain viewport, but it seem to break-off in different viewports.

I know it is not right way, I end up writing too much CSS and still doesn't look consistent on different viewports.

Getting the Logo perfectly on the center and aligning them vertically is where I'm struggling.

Here is the HTML code.

<nav class="navbar">
<div class="sidebar-toggle">
<button class="sidebar-toggler" type="button">☰</button>
</div>
<div class="headerLogo">
<a href="" class="logo">Logo</a>
</div>
<div class="headerLinks">
<a href="">link1</a>
<a href="">link2</a>
</div>
<div class="notifications">
<div class="mailIcon"></div>
</div>
</nav>

Answer

You can just use justify-content: space-between and get right spacing and align-items: center for vertical align.

.navbar,
.links {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
<nav class="navbar">
  <div class="sidebar-toggle">
    <button class="sidebar-toggler" type="button">☰</button>
  </div>
  <div class="headerLogo">
    <a href="" class="logo">Logo</a>
  </div>
  <div class="links">
    <div class="headerLinks">
      <a href="">link1</a>
      <a href="">link2</a>
    </div>
    <div class="notifications">
      <div class="mailIcon">Mail</div>
    </div>
  </div>
</nav>

If you want logo perfectly centered then you need to remove it from elements flow with position: absolute;

.navbar,
.links {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
}
.headerLogo {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<nav class="navbar">
  <div class="sidebar-toggle">
    <button class="sidebar-toggler" type="button">☰</button>
  </div>
  <div class="headerLogo">
    <a href="" class="logo">Logo</a>
  </div>
  <div class="links">
    <div class="headerLinks">
      <a href="">link1</a>
      <a href="">link2</a>
    </div>
    <div class="notifications">
      <div class="mailIcon">Mail</div>
    </div>
  </div>
</nav>

Comments