CSS Navigation
Having easy-to-use navigation is important for any web site.
With CSS you can transform boring HTML menus into good-looking navigation bars.
Navigation Bar = List of Links
A navigation bar needs standard HTML as a base.
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:
Example:
<ul>
<li><a href="index.html">Home</a>>/li>
<li><a href="news.html">News</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="about.html">About</a></li>
</ul>
The CSS navigation bar
1. Structure with HTML
- Use a container element like <nav> or a <div> to hold the navigation links.
- Use an unordered list <ul> and list items <li> for each navigation link to ensure a semantic structure.
- Anchor tags <a> inside the list items are used for the actual navigation links.
2. Layout and Display Properties
- Horizontal vs. Vertical: Use display: inline; for horizontal lists and display: block; for vertical lists.
- Flexbox or Grid: Use display: flex; or display: grid; to align and distribute items efficiently.
- Positioning: Consider using position: fixed; or position: sticky; to make the navbar stay at the top of the page when scrolling.
3. Styling Links
- Text Decoration: Use text-decoration: none; to remove the underline from links.
-
Padding and Margin: Add space around links to improve clickability and visual separation.
-
Hover Effects: Use :hover pseudo-class to change the appearance of links when hovered over.
- Active State: Style the currently active link differently using the :active or custom class to indicate the active page.
4. Background and Color
- Background Color: Apply a background color to the navbar using background-color.
- Text Color: Ensure good contrast between the text color and the background color for readability.
- Hover and Active Colors: Use different colors for hover and active states to improve user feedback.
5. Dropdown Menus
- Use nested <ul> elements for dropdowns.
- Style dropdown menus to appear on hover using the :hover pseudo-class.
- Use position: absolute; to make dropdowns appear below their parent items.
6. Responsive Design
- Use media queries to adjust the layout on smaller screens.
- Hamburger Menu: Implement a collapsible or hamburger menu for mobile navigation.
- Hide or Stack: Stack navigation links vertically or hide them under a menu icon when the screen size reduces.
7. Accessibility
- Use ARIA attributes for better screen reader support (e.g., aria-label, aria-expanded).
- Ensure keyboard navigation is possible, especially for dropdown menus.
- Provide clear focus states for better accessibility.
8. Customizations and Enhancements
- Icons: Use icons (e.g., from FontAwesome) to represent links visually.
- Animation: Add subtle animations or transitions for hover and dropdown effects.
- Shadow and Border Effects: Use box-shadow or borders for a more appealing design.