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

วิธีกำหนดสื่อ/อุปกรณ์ที่เอกสารลิงก์เหมาะสมใน HTML

ใช้แอตทริบิวต์ media เพื่อระบุสื่อ/อุปกรณ์ที่เอกสารลิงก์ได้รับการปรับให้เหมาะสมใน HTML แอตทริบิวต์นี้ใช้ได้กับองค์ประกอบ <a>, <area>, <link> ฯลฯ

ตัวอย่าง

<html>
  <head>
    <title>HTML media attribute</title>
    <link rel="stylesheet" href="style.css" media="screen" />
    <link rel="stylesheet" href="print.css" media="print" />
    <link rel="stylesheet" href="mobile.css" media="screen and (max-width: 768px)" />
  </head>
  <body>
    <p>This is demo text.</p>
  </body>
</html>

ค่า Media Types ที่ใช้บ่อย

Media Type คำอธิบาย
all ทุกอุปกรณ์ (ค่าเริ่มต้น)
screen หน้าจอคอมพิวเตอร์/มือถือ/แท็บเล็ต
print เครื่องพิมพ์ / Print Preview
speech Screen readers / Speech synthesizers

Media Queries (Responsive)

<!-- Mobile First -->
<link rel="stylesheet" href="base.css" media="all">
<link rel="stylesheet" href="tablet.css" media="screen and (min-width: 768px)">
<link rel="stylesheet" href="desktop.css" media="screen and (min-width: 1024px)">

<!-- Orientation -->
<link rel="stylesheet" href="portrait.css" media="screen and (orientation: portrait)">
<link rel="stylesheet" href="landscape.css" media="screen and (orientation: landscape)">

<!-- High DPI / Retina -->
<link rel="stylesheet" href="retina.css" media="screen and (min-resolution: 2dppx)">

<!-- Dark Mode -->
<link rel="stylesheet" href="dark.css" media="screen and (prefers-color-scheme: dark)">
<link rel="stylesheet" href="light.css" media="screen and (prefers-color-scheme: light)">

<!-- Reduced Motion -->
<link rel="stylesheet" href="reduced-motion.css" media="screen and (prefers-reduced-motion: reduce)">

ใช้กับ <a> และ <area>

<!-- ลิงก์เฉพาะสำหรับ Print -->
<a href="print-version.html" media="print">Print Version</a>

<!-- Image Map สำหรับอุปกรณ์ต่างๆ -->
<img src="map.jpg" usemap="#map">
<map name="map">
  <area shape="rect" coords="0,0,100,100" href="mobile.html" media="screen and (max-width: 600px)">
  <area shape="rect" coords="0,0,100,100" href="desktop.html" media="screen and (min-width: 601px)">
</map>

ใน CSS (@media vs link media)

<!-- External file: โหลดเฉพาะเมื่อ match -->
<link rel="stylesheet" href="print.css" media="print">

<!-- Inline/Embedded: โหลดเสมอ แต่ apply เฉพาะเมื่อ match -->
<style>
  @media print {
    .no-print { display: none; }
  }
</style>

ข้อแตกต่าง: <link media> เบราว์เซอร์จะไม่ดาวน์โหลดไฟล์ถ้าไม่ match (Performance ดีกว่า) ส่วน @media ใน CSS จะดาวน์โหลดไฟล์ CSS ทั้งหมด