Recently I was building a navigation bar for one onsite project. Here I share how I used flex-direction property to make my website responsive. It’s important because all new mobile devices are built with varying screen sizes. The screen orientation is switchable between portrait and landscape.
Steps to build a responsive navigation bar.
- Place <nav/> tag inside <header/> tag in your HTML index file.
- Use <ul/> tag. Place <a/> tag inside list item <li/> tag. <a/> tag will store links to page sections.
<header>
<nav class=”nav-right”>
<ul id=’nav-container’>
<li><a href=’#about’>About</a></li>
<li><a href=’#projects’>Projects</a></li>
<li><a href=’#blog’>Blog</a></li>
<li><a href=’#conact’>Contact</a></li>
</ul>
</nav>
<header/>
3. Place basic CSS styling rules:
#nav-container {
display: flex;
flex-direction: row; //same as text direction
align-items: flex-end;
justify-content: flex-end;
background-color: #1b242f;
color: white;
padding-right: 20px;
text-transform: uppercase;
list-style: none;
margin: 0
}
ul li {
padding: 10px 10px;
}
ul li a {
color: white;
line-height: 1.5em;
text-decoration: none;
}
4. If you are done with the navigation section, start constructing rules for different screen sizes.
To adapt our navigation bar to a different screen size I use media query. Media Queries defines a syntax for short expressions that describe required features of media (or devices), e.g.: minimum or maximum screen size, color capabilities, etc.
//Change the flex-direction when the browser window is 500px wide or less:@media screen and (max-width: 500px) {
#nav-container {
flex-direction: column; //same as row but top to bottom
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
}
Flex direction
By definition the flex
property sets the flexible length on flexible items. The main axis and cross axis can be toggled based on the flex-direction being set to either a column or row. So the main axis is always the horizontal axis by default, unless you use flex-direction: column-
and the vertical axis becomes the main axis. In my example I used the property flex-direction: column
to change the appearance of the navigation bar on the devices with the screens smaller than 500px.
The CSS Flexible Box Module (flexbox for short), makes the once-difficult task of laying out your page simple. With flexbox, layout is so simple you won’t need a CSS framework.