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

วิธีใช้แท็ก base กำหนด Base URL สำหรับ Relative Links ใน HTML

แท็ก <base> กำหนด Base URL สำหรับ relative URLs ทั้งหมดในหน้าเว็บ วางใน <head> มีได้เพียง 1 ต่อหน้า

Attribute

Attributeค่าคำอธิบาย
hrefURLBase URL สำหรับ relative links ทั้งหมด
target_blank, _self, _parent, _topDefault target สำหรับ links ทั้งหมด

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <title>HTML base Tag</title>
  <base href="https://www.example.com/docs/" target="_blank">
</head>
<body>
  <p>HTML: <br><img src="images/html.gif"> <!-- resolves to https://www.example.com/docs/images/html.gif --></p>
  <p><a href="css/guide.html">CSS Guide</a> <!-- opens in new tab due to base target --></p>
</body>
</html>

ผลลัพธ์

  • <img src="images/html.gif"> → https://www.example.com/docs/images/html.gif
  • <a href="css/guide.html"> → https://www.example.com/docs/css/guide.html (opens in new tab)

ข้อควรระวัง

  • มีได้เพียง 1 ต่อหน้า** - วางใน <head> ก่อน relative URLs อื่นๆ
  • ส่งผลต่อ ทุก relative URLs: <a>, <img>, <link>, <script>, <form action>
  • Absolute URLs (ขึ้นต้น https://, https://, //) ไม่ได้รับผลกระทบ
  • Anchor links (#section) ไม่ได้รับผลกระทบ
  • อาจสับสน developer คนอื่น - ใช้เฉพาะเมื่อจำเป็นจริง

กรณีใช้งาน

  • Static site hosting ใน subdirectory
  • Template systems ที่รวม partials
  • Email HTML (บาง client ต้องการ absolute URLs)