Two methods exist for creating a horizontal navigation bar: utilizing inline or floating list items.
For the inline list items approach, you can construct a horizontal navigation bar by setting the <li> elements to display inline, in conjunction with the “standard” code from the preceding page.
Example
li { display: inline; } |
Explanation of the example:
Alternatively, for the floating list items method:
Example
li { float: left; } a { display: block; padding: 8px; background-color: #dddddd; } |
Explanation of the example:
Tip: To achieve a full-width background color, consider applying the background-color to <ul> instead of individually to each <a> element.
Example
ul { |
Craft a simple horizontal navigation bar featuring a dark background color, and alter the background color of the links upon mouse hover.
Example
ul { |
Include an “active” class to the current link to indicate to the user which page they are currently on.
Example
.active { |
Achieve right alignment of links by floating the list items to the right using float:right;.
Example
<ul> |
Apply the border-right property to <li> elements to establish link separators.
Example
/* Add a gray right border to all list items, except the last item (last-child) */ |
Ensure that the navigation bar remains fixed at either the top or bottom of the page, regardless of the user’s scrolling action.
Please note that fixed positioning may not function correctly on mobile devices. |
An illustration showcasing a horizontal navigation bar with a gray hue and a subtle gray border.
Example
ul { border: 1px solid #e7e7e7; background-color: #f3f3f3; } li a { color: #666; } |
Include position: sticky; to the <ul> element to implement a sticky navbar.
A sticky element transitions between relative and fixed positioning based on the scroll position. Initially positioned relatively, it switches to a fixed position once it reaches a specified offset in the viewport, effectively “sticking” in place similar to position: fixed.
Example
ul { |
Please note that Internet Explorer does not support sticky positioning, while Safari requires a `-webkit-` prefix (as illustrated in the example above). Additionally, for sticky positioning to function properly, you must specify at least one of the following: top, right, bottom, or left. |