Home > Web Front-end > CSS Tutorial > How Can I Perfectly Justify a Horizontal Text-Only Menu in HTML and CSS?

How Can I Perfectly Justify a Horizontal Text-Only Menu in HTML and CSS?

DDD
Release: 2024-12-03 05:38:15
Original
956 people have browsed it

How Can I Perfectly Justify a Horizontal Text-Only Menu in HTML and CSS?

Justifying Horizontal Menus in HTML CSS: A Comprehensive Solution

Despite the abundance of tutorials on menu bars in HTML, achieving optimal justification for text-only menus remains a challenge. This article will present a robust solution that ensures proper alignment, optimal spacing, and flexibility for varying menu item counts.

Understanding the Problem

The goal is to create a horizontal menu where:

  • The first item is left-aligned
  • The last item is right-aligned
  • Remaining items are evenly distributed across the menu bar
  • The solution should work with varying numbers of items without pre-calculating optimal widths

The Invisible Expansion Span

The key to achieving this justification is to insert an invisible element at the end of the menu that forces a line break. By strategically hiding this element, we can create the necessary space for optimal item distribution.

Here's the optimal CSS and HTML code:

#menu {
  text-align: justify;
}

#menu * {
  display: inline;
}

#menu li {
  display: inline-block;
}

#menu span {
  display: inline-block;
  position: relative;
  width: 100%;
  height: 0;
}
Copy after login
<div>
Copy after login

How it Works

  1. #menu sets the justification for the entire menu.
  2. #menu * ensures all children are inline elements.
  3. #menu li makes menu items inline-blocks, allowing them to flow horizontally.
  4. The hidden span (#menu span) expands to fill the remaining space, forcing a line break and making the menu justify properly.

This solution provides an elegant and effective way to create justified horizontal menus in HTML CSS, ensuring optimal spacing and alignment regardless of the number of menu items.

The above is the detailed content of How Can I Perfectly Justify a Horizontal Text-Only Menu in HTML and CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template