Horizontal Navigation With White-Space
Are you wondering on how to achieve a navigation links that align straight and does not wrap the content?
This guide provides instructions to achieve with white-space css property.
Initial setup
For our initial setup, we need to create index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body style="width: 640px; margin: auto;"> <nav> <ul style="display: flex; gap: 1.5rem;"> <li>Home</li> <li>About</li> <li>Social Medias</li> <li>Etc.</li> <li>Random Long Words</li> <li>Example For Reference</li> </ul> </nav> </body> </html>
When we open the index.html, it should look like this:
Solution
The solution for this problem is to add white-space css property with nowrap on the ul element.
<ul style="display: flex; gap: 1.5rem; white-space: nowrap;"> ... </ul>
Result:
Bonus
Here some bonus section, let say we have limited space on our screen and our navigation has property white-space set to nowrap. As a result, the navigation causes horizontal scrolling throughout the entire screen.
Solution: add a parent element to wrap your navigation links. On parent element, add overflow-x CSS property with a value of scroll.
With our example, we already wrap our navigation links with nav tag.
<nav style="overflow-x: scroll;"> <ul style="display: flex; gap: 1.5rem;"> ... </ul> </nav>
Result: Instead of scrolling horizontally through our entire screen, we can apply horizontal scrolling specifically to our navigation links.
I hope this guide helps you in your Frontend Journey!