- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a navigation bar with left-aligned and right-aligned links with CSS?
With CSS, we can easily create a navigation bar i.e., a menu. Also, links can be left or right-aligned. We will use flex to achieve the same. Let us see how.
Create a Navigation bar Using <nav>
The <nav> element is used to create a navigation bar on the web page. The links are set in between −
<nav> <! -- set the div for links --> </nav>
Navigation bar With Flex and Position Fixed
The display is set to flex.The position is set fixed using the fixed value of the position property −
nav { display: flex; position: fixed; top:0; width: 100%; background-color: rgb(251, 255, 196); overflow: auto; height: auto; }
Set the div for Left Links
The following menu links are placed on the left side of the web page −
<div class="left-links"> <a class="links selected" href="#">Home</a> <a class="links" href="#"> Login</a> <a class="links" href="#"> Register</a> </div>
Set the div for the Right Links
The following menu links are placed on the right side of the web page −
<div class="right-links"> <a class="links" href="#"> Contact Us</a> <a class="links" href="#">More Info</a> </div>
Link is Aligned to the Left With Flex
With the flex property, set the Home, Login and Register links to the left. The initial length of the left flexible item is set to 200px −
.left-links{ flex:1 1 200px; }
The following is the code to create a navigation bar with left-aligned and right-aligned links −
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <style> body{ margin:0px; margin-top:60px; padding: 0px; } nav{ display: flex; position: fixed; top:0; width: 100%; background-color: rgb(251, 255, 196); overflow: auto; height: auto; } .left-links{ flex:1 1 200px; } .links { display: inline-block; text-align: center; padding: 14px; color: rgb(0, 0, 0); text-decoration: none; font-size: 17px; font-weight: bolder; } .links:hover { border-bottom: 2px solid purple; } .selected{ border-bottom: 2px solid purple; } </style> </head> <body> <nav> <div class="left-links"> <a class="links selected" href="#">Home</a> <a class="links" href="#"> Login</a> <a class="links" href="#"> Register</a> </div> <div class="right-links"> <a class="links" href="#"> Contact Us</a> <a class="links" href="#">More Info</a> </div> </nav> <h1>Hover on the above links</h1> </body> </html>
Advertisements