บทนำ
แอตทริบิวต์ height และ width ระบุความสูงและความกว้างขององค์ประกอบในหน่วย Pixel (px)
องค์ประกอบที่รองรับ
| ลำดับ | Element | height | width |
|---|---|---|---|
| 1 | <canvas> | ✓ | ✓ |
| 2 | <embed> | ✓ | ✓ |
| 3 | <iframe> | ✓ | ✓ |
| 4 | <img> | ✓ | ✓ |
| 5 | <input> (type=image) | ✓ | ✓ |
| 6 | <object> | ✓ | ✓ |
| 7 | <video> | ✓ | ✓ |
| 8 | <svg> | ✓ | ✓ |
ตัวอย่างกับ <img>
<!DOCTYPE html>
<html>
<head>
<title>HTML Height Width Attribute</title>
</head>
<body>
<img src="https://example.com/logo.png" alt="Logo" width="200" height="70">
</body>
</html>
แนวทางปฏิบัติที่ดี
- ระบุ width/height ทุกครั้งสำหรับ
<img><video><iframe>เพื่อป้องกัน Layout Shift (CLS) - ใช้ CSS สำหรับ Responsive:
width: 100%; height: auto; <canvas>ต้องตั้ง width/height attribute (ไม่ใช่ CSS) เพื่อกำหนด Resolution จริง
Canvas: Attribute vs CSS
<!-- Attribute = Resolution จริง (Drawing Surface) -->
<canvas width="800" height="600"></canvas>
<!-- CSS = ขนาดแสดงผล (Display Size) -->
<canvas style="width: 400px; height: 300px;"></canvas>