Have you started hacking with CSS recently and wanted to display a list or menu in a horizontal fashion? Then you are at the right place. In this article, we will explore different ways to display a horizontal list in HTML.
Project setup
Below will be the HTML code we will be using throughout this article:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal List</title>
<style></style>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
</body>
</html>
The above HTML will render the page as shown below:
Using display inline
<!DOCTYPE html>
<html>
<head>
<title>Horizontal List</title>
<style>
li {
display: inline-block;
}
</style>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
</body>
</html>
If you add display:inline-block
style as shown below, the items will be aligned next to each other:
Let's add some styling to the menu:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal List</title>
<style>
li {
display: inline-block;
padding: 1rem;
}
li a {
color: white;
text-decoration: none;
}
li a:hover {
color: #333;
}
ul {
background: teal;
margin: 0;
text-align: center;
}
</style>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
</body>
</html>
If you run the code now, you will get:
Using display flex
We can make the ul
element flex to align the menu horizontally:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal List</title>
<style>
ul {
display: flex;
}
li {
list-style-type: none;
padding: 1rem;
}
li a {
color: white;
text-decoration: none;
}
li a:hover {
color: #333;
}
ul {
background: teal;
margin: 0;
text-align: center;
padding-left: 0;
}
</style>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
</body>
</html>
Using grid
You can use the CSS grid as shown below to align the items horizontally:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal List</title>
<style>
ul {
display: grid;
grid-template-columns: auto auto auto auto;
}
li {
list-style-type: none;
padding: 1rem;
}
li a {
color: white;
text-decoration: none;
}
li a:hover {
color: #333;
}
ul {
background: teal;
margin: 0;
text-align: center;
padding-left: 0;
}
</style>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
</body>
</html>
Top comments (0)