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

Các loại List trong HTML

Có ba loại danh sách (list) trong HTML:

  • Unordered list <ul> — Danh sách không thứ tự, dùng bullet (chấm tròn, vuông...)
  • Ordered list <ol> — Danh sách có thứ tự, dùng số, chữ cái, số La Mã...
  • Definition list <dl> — Danh sách định nghĩa, gồm cặp <dt> (term) và <dd> (description)

Chúng ta có thể lồng (nest) các list này và style chúng theo ý muốn. Thuộc tính CSS list-style giúp chúng ta style các mục danh sách.

Cú pháp cơ bản

<type of list>
    <li></li>
</type of list>

Ví dụ 1: ul và ol lồng nhau

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    background-color: papayawhip;
    list-style-type: square;
    font-style: italic;
}
ol { background-color: azure; }
</style>
</head>
<body>
<ol>
    <li>demo1</li>
    <li> demo 2
        <ul>
            <li>demo a</li>
            <li>demo b</li>
        </ul>
    </li>
    <li>demo 3</li>
</ol>
</body>
</html>

Ví dụ 2: Definition list (dl)

<!DOCTYPE html>
<html>
<head>
<style>
dt { font-weight: bold; font-style: italic; }
dd { border: thin dotted; margin-left: 1rem; padding: 0.5rem; }
</style>
</head>
<body>
<h2>Programming Languages and Databases</h2>
<dl>
    <dt>Java</dt>
    <dd>Ngôn ngữ lập trình do James Gosling phát triển.</dd>
    <dt>C++</dt>
    <dd>Ngôn ngữ lập trình do Bjarne Stroustrup phát triển.</dd>
    <dt>MySQL</dt>
    <dd>Hệ quản trị CSDL quan hệ mã nguồn mở.</dd>
</dl>
</body>
</html>

CSS list-style properties

Thuộc tínhMô tảGiá trị mẫu
list-style-typeKiểu markerdisc, circle, square, decimal, lower-roman, upper-alpha, none
list-style-positionVị trí markeroutside (mặc định), inside
list-style-imageHình ảnh làm markerurl("bullet.png")
list-styleShorthandtype position image

Nesting Lists Best Practice

/ * Reset margin cho list lồng nhau */
ul ul, ol ol, ul ol, ol ul {
    margin-top: 0;
    margin-bottom: 0;
    padding-left: 1.5rem; /* hoặc 2ch */
}

/ * Style khác cho từng level */
ol { list-style-type: decimal; }
ol ol { list-style-type: lower-alpha; }
ol ol ol { list-style-type: lower-roman; }