Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งาน CSS list-style-image Property

บทนำ

Property list-style-image ใช้กำหนดรูปภาพเป็นเครื่องหมายรายการ (bullet) แทนจุดหรือตัวเลขปกติ

ตัวอย่างโค้ด

<html>
<head></head>
<body>
  <ul>
    <li style="list-style-image: url(/images/bullet.gif);">Karnataka</li>
    <li>Hyderabad</li>
  </ul>
</body>
</html>

คำอธิบาย

  • url(/images/bullet.gif) - พาธของไฟล์รูปภาพ (relative หรือ absolute)
  • รูปภาพควรเล็ก (16x16px - 32x32px) และโปร่งใส (PNG/GIF/SVG)
  • ถ้ารูปโหลดไม่ได้ จะ fallback เป็น list-style-type

Syntax

list-style-image: none | url('path/to/image');

Best Practices

/* แนะนำ: ระบุ fallback type */
ul.custom-bullets {
  list-style-image: url('bullet.svg');
  list-style-type: disc; /* fallback */
  list-style-position: outside;
}

/* ใช้กับ ol ได้เช่นกัน */
ol.custom-numbers {
  list-style-image: url('number-icon.png');
}

การจัดตำแหน่งรูปภาพ

รูปภาพจะจัดอยู่ตาม list-style-position:

  • outside (ค่าเริ่มต้น) - รูปอยู่นอก content box
  • inside - รูปอยู่ใน content box

ตัวอย่างสมบูรณ์

<style>
  .custom-list {
    list-style-image: url('data:image/svg+xml;utf8,');
    list-style-position: outside;
    padding-left: 20px;
  }
</style>

<ul class="custom-list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

ข้อจำกัด

  • ไม่สามารถปรับขนาดรูปได้ด้วย CSS (ต้องปรับจากไฟล์ต้นฉบับ)
  • ไม่สามารถจัดตำแหน่ง micro-adjust ได้ (ใช้ background-image แทนถ้าต้องการควบคุมเต็มที่)
  • SVG แนะนำกว่า PNG/GIF เพราะ scale ได้ไม่เสียคุณภาพ

Alternative: ใช้ ::marker หรือ background

/* Modern way - ใช้ ::marker pseudo-element */
li::marker {
  content: url('bullet.svg');
}

/* ควบคุมได้มากกว่า - ใช้ background */
li {
  list-style: none;
  padding-left: 24px;
  background: url('bullet.svg') left center no-repeat;
  background-size: 16px 16px;
}