Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Xây dựng thanh điều hướng ngang với Inline List Items trong CSS

Horizontal Navigation Bar với Inline List

Chuyển `

  • ` thành `display: inline` (hoặc `inline-block`/`flex`) để hiển thị ngang. Kết hợp `
      ` reset margin/padding/list-style.

      Ví dụ cơ bản

      <!DOCTYPE html>
      <html>
      <head>
        <style>
          ul {
            list-style-type: none;  /* Bỏ bullet */
            margin: 0;
            padding: 0;
          }
          .active {
            background-color: #4CAF50;
            color: white;
          }
          li {
            border-bottom: 1px solid #555;
            display: inline;        /* Quan trọng: hiển thị ngang */
          }
          li a {
            display: inline-block;  /* Cho phép padding click area */
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            background-color: #333;
          }
          li a:hover { background-color: #555; }
        </style>
      </head>
      <body>
        <ul>
          <li><a href="#home">Home</a></li>
          <li><a href="#company" class="active">Company</a></li>
          <li><a href="#product">Product</a></li>
          <li><a href="#services">Services</a></li>
          <li><a href="#contact">Contact</a></li>
        </ul>
      </body>
      </html>

      Cải tiến: Flexbox Navigation (Hiện đại, khuyên dùng)

      .nav {
        display: flex;
        list-style: none;
        margin: 0;
        padding: 0;
        background: #333;
        gap: 0; /* hoặc dùng border-right trên li */
      }
      .nav li { flex: 1; } /* Chia đều không gian */
      .nav a {
        display: block;
        padding: 16px;
        color: white;
        text-decoration: none;
        text-align: center;
        transition: background 0.2s;
      }
      .nav a:hover,
      .nav .active a { background: #4CAF50; }
      
      /* Responsive: Mobile hamburger */
      @media (max-width: 768px) {
        .nav { flex-direction: column; }
        .nav li { border-bottom: 1px solid #444; }
      }
      

      So sánh: inline vs inline-block vs flex

      DisplayPadding verticalWidth/HeightWhitespaceVertical align
      inline❌ Không hoạt động❌ Không set đượcCó gap do whitespace HTMLbaseline
      inline-block✅ Hoạt động✅ Set đượcCó gap (fix: font-size: 0 trên cha)Có thể set
      flex (trên ul)✅ Hoạt động✅ Tự động/flex❌ Không gapDễ dàng (align-items)

      Accessibility (A11y) cho Navigation

      <nav aria-label="Main navigation">
        <ul class="nav">
          <li><a href="#home" aria-current="page">Home</a></li>
          <li><a href="#about">About</a></li>
          <li><a href="#services">Services</a></li>
          <li><a href="#contact">Contact</a></li>
        </ul>
      </nav>
      

      Lưu ý