Table of Contents
Lists in HTML are useful because you can use them to display several pieces of related information.
However, by default, lists are rendered vertically, from top to bottom.
Sometimes you might want to display a list horizontally, from left to right, for example like for a menu of a website.
In this post, we'll learn how to display a list horizontally using CSS.
How to display a list horizontally using CSS
To start, first let's create a simple HTML list:
HTML<body>
<h1>My Website</h1>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</body>
This will render like this:
- HTML
A quick way to display a list horizontally is to use the CSS property display: flex
on the list's parent element.
Let's add a class to the parent to do that:
HTML<body>
<h1>My Website</h1>
<ul class="parent">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</body>
CSS.parent {
display: flex;
}
That looks like this:
- HTML
- CSS
We can further improve the look of the list by adding a class to each item in the list and then styling them like this:
HTML<body>
<h1>My Website</h1>
<ul class="parent">
<li class="child">Home</li>
<li class="child">About</li>
<li class="child">Contact</li>
</ul>
</body>
CSS.parent {
display: flex;
list-style: none;
padding: 0;
}
.child {
background-color: #eee;
padding: 0.5rem 0.75rem;
}
- HTML
- CSS
As you can see, the list is now displayed horizontally and can be expanded on further to make it look like a navigation menu.
Conclusion
In this post, we learned how to display a list horizontally using CSS.
Simply add the CSS property display: flex
to the parent element of the list and you're good to go, then style the list items as you wish.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript