How to create a horizontal list using HTML and CSS

📋 Table Of Content
In this post, we will learn how to create and display list horizontally in CSS.
In HTML, to create any list of items we use the <ul>
or <ol>
tags, and all the list items are written inside the <li>
tags. And this will render the list vertically on our web page. For example,
<ul>
<li>One</li>
<li>two</li>
<li>Three</li>
</ul>
This will create a vertical list like this
Now, let's say we need to create a navigation bar on our website and we need to display the list horizontally.
To do that we have two ways:
- Using inline-block, and
- Using flex-box
Let's check each method with an example
Using inline-block to display list horizontally
The inline-block
property displays the element as an inline-level block container. So when an element is set as display:inline-block
, we can set the height and width to it.
So, let's say we have a list of page links for our navigation bar on the website.
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
So make it horizontally aligned, we just need to set <li>
to display:inline-block
in our style sheet.
<style>
li{
display:inline-block;
}
</style>
Now our links are displayed horizontally. We can add some background, width, and margin to make it look good too.
Output:
Read more about inline-block property : Difference between block, inline and inline-block display in CSS
Using flex-box to make a horizontal list
To align the list horizontally using flex-box we just have to set the parent element as display: flex
.
Here, the parent element is the <ul>
element. So we just have to set it to display:flex and all the child elements i.e <li>
tags will be displayed horizontally.
Example
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
And the CSS will be
ul{
display:flex;
}
li{
width: 80px;
background: lightgreen;
margin-right: 10px;
list-style: none
}
The output will be like this
With flex-box we can also use other useful property like justify-content
that helps us to properly give spaces between the child elements.
Example 1:
Using justify-content: space-between
in the parent element i.e the <ul>
tag.
ul{
display:flex;
justify-content: space-between;
}
Output:
The space-between
lets the items be evenly distributed in a line.
Example 2:
Using justify-content: space-around
in the parent element i.e the <ul>
tag.
ul{
display:flex;
justify-content: space-around;
}
Output:
The space-around
lets the child items be distributed in a line with equal spaces around them.
Read More about flex-box A Complete Guide to Flexbox | CSS-Tricks
Related Topics:
How to make a collapsible list in HTML without JavaScript
Difference between block, inline and inline-block display in CSS