The Easiest Way To Make Responsive Headers

Making pretty, responsive, headers is always a tricky process. Until now you needed to use floats or other complicated tricks and you even had to manually adjust pixel values. But not any more!

The technique we are about to show you relies on the powerful flexbox layout mode to do all the dirty work for you. It uses just a handful of CSS properties to create a header that is properly aligned and looks good on all screen sizes, while leaving the code cleaner and less hacky.


The Technique

In our demonstrative example we’ve built a header, which is separated in three sections with typical header content nested within them:
  • Left section – The company logo.
  • Middle section – Various hyperlinks.
  • Right section – A button.
You can check out a simplified version of the code bellow.

HTML code is where we group the sections in separate div tags. This makes it easier for CSS rules to be applied and generally produces a more organised code.

 <header>  
      <div class="header-left">CoolLogo</div>  
      <div class="header-center">  
           <ul>  
                <li><a href="#">Our products</a></li>  
                <li><a href="#">Pricing</a></li>  
                <li><a href="#">Blog</a></li>  
           </ul>  
      </div>  
      <div class="header-right"><button>Buy now</button></div>  
 </header>  

CSS is just a couple of lines, does the entire job of finding the right places for the each of the sections.

 header{  
      /* Enable flex mode. */  
      display: flex;   
      /* Spread out the elements inside the header. */  
      justify-content: space-between;  
      /* Align items vertically in the center. */  
      align-items: center;  
 }  

Full responsiveness

The space-between trick will always take care of the alignment, even when the screen size changes. However, when the viewport becomes too small for a horizontal header, we can make it go vertical by changing the flex-direction property in a media query.

 @media (max-width: 1000px){  
      header{  
           /* Reverse the axis of the header, making it vertical. */  
           flex-direction: column;  
           /* Align items to the begining (the left) of the header. */  
           align-items: flex-start;  
      }  
 }  

Conclusion

This sums up our quick tutorial! Flexbox has pretty good browser support nowadays, so unless your user base is IE heavy, this technique can be applied without causing any mayhem.

Comments

Popular posts from this blog

Gradient Border Colors with CSS

10 Useful Libraries and Resources for Responsive Web Design

The Simplest Way To Center Elements Vertically And Horizontally