Explain Codes LogoExplain Codes Logo

Horizontal list items

html
responsive-design
best-practices
web-development
Nikita BarsukovbyNikita Barsukov·Nov 11, 2024
TLDR

Convert your list into a horizontal lineup using display: inline-block on the <li> elements. It aligns list items into a flawless row.

Example:

<ul style="list-style: none; padding: 0;"> <li style="display: inline-block; margin-right: 10px;">Item 1</li> <!-- Traveler 1 --> <li style="display: inline-block; margin-right: 10px;">Item 2</li> <!-- Traveler 2 --> <li style="display: inline-block; margin-right: 10px;">Item 3</li> <!-- Traveler 3, now boarding and ready for takeoff! --> </ul>

This crisp CSS technique arranges items horizontally with harmonious spacing, eliminating default list styles for a better horizontal layout.

Modern methods: Flexbox

display: flex;, an advanced layout method, offers an adaptive and responsive horizontal list. Set this property on the <ul> or <ol> container to enable various layout configurations and alignments.

<ul style="display: flex;"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>

Abstaining from floats

Back in the day, float: left; was used for horizontal alignment of list items. However, this method may cause layout issues and requires clearing floats — a cumbersome process. Modern methods such as flex or inline-block offer a cleaner and more efficient solution.

/* Let's keep the past in the past and ditch floats! */ li { float: none; }

Supporting older browsers

When targeting audience on outdated Internet Explorer versions, test your horizontal list layout for compatibility. If needed, apply specific fallbacks or prefixes.

The importance of margins & alignment

For a visually appealing horizontal list, the margin-right and vertical-align properties are your best friends. They help fine-tune the spacing and alignment of the list items.

li { display: inline-block; margin-right: 20px; /* Space, the final frontier. */ vertical-align: top; } li:last-child { margin-right: 0; /* Last one in line doesn't need space on the right. */ }

Cross-browser testing

Do not let the appearance of your list play hide and seek across different browsers and devices. Make sure to test for consistent display.

/* Because not all browsers speak the same language. */ ul, li { margin: 0; padding: 0; }