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

HTML5 Semantic Elements và hỗ trợ trình duyệt cũ (IE8-)

HTML5 giới thiệu các semantic elements (<header>, <footer>, <nav>, <section>, <article>, <aside>, <main>, <figure>, <figcaption>, <time>, <mark>...). IE8 và cũ hơn không nhận diện các thẻ này → không áp dụng CSS, không tạo DOM đúng.

Giải pháp 1: CSS Reset - Ép display block (Đơn giản)

/* Phải khai báo trước CSS khác */
article, aside, details, figcaption, figure, 
footer, header, hgroup, main, menu, nav, section, summary {
  display: block;
}

/* HTML5 hidden attribute */
[hidden] { display: none; }

Giải pháp 2: HTML5 Shiv / Shims (Tạo element qua JS - Bắt buộc cho IE6-8)

IE không cho style element chưa biết trừ khi tạo qua document.createElement().

<!--[if lt IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
<![endif]-->

html5shiv tạo sẵn tất cả HTML5 elements khi load trang.

Giải pháp 3: Tự tạo element (Không cần thư viện)

<!--[if lt IE 9]>
  <script>
    var elements = 'article,aside,figcaption,figure,footer,header,hgroup,main,mark,menu,nav,section,summary,time,details,dialog'.split(',');
    for (var i = 0; i < elements.length; i++) {
      document.createElement(elements[i]);
    }
  </script>
<![endif]-->

Giải pháp 4: Modernizr (Feature Detection)

<script src="modernizr-custom.js"></script>
// Modernizr thêm class 'html5shiv' vào html tag nếu cần
// Cũng detect feature: canvas, geolocation, localstorage, v.v.

Danh sách Semantic Elements HTML5 chính

ElementÝ nghĩaVí dụ dùng
<header>Header trang hoặc sectionLogo, nav, heading
<nav>Navigation linksMenu chính, breadcrumb
<main>Nội dung chính duy nhấtWrapper content chính
<article>Nội dung độc lập, có thể syndicateBài blog, bài báo, comment
<section>Khối nội dung có chủ đềChương, tab panel
<aside>Nội dung phụ, sidebarQuảng cáo, related posts
<footer>Footer trang hoặc sectionCopyright, contact, links
<figure>/<figcaption>Hình ảnh/ký tự + chú thíchChart, code snippet, photo
<time>Thời gian/ngày tháng machine-readable<time datetime="2024-01-15">15/01/2024</time>

Lợi ích Semantic HTML

  • SEO: Google hiểu cấu trúc nội dung tốt hơn.
  • Accessibility: Screen reader duyệt landmarks (nav, main, aside).
  • Maintainability: Code đọc hiểu dễ dàng.
  • RSS/Reader mode: Trích xuất content chính chính xác.

Kiểm tra hỗ trợ

Can I Use: html5semantic - Tất cả browser hiện đại hỗ trợ đầy đủ. Chỉ IE8- cần shiv.