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

เพิ่มความกว้างในหน่วยตัวอักษรสำหรับ input ด้วยแอตทริบิวต์ size

แอตทริบิวต์ size ของ <input type="text"> (และประเภทข้อความอื่นๆ) ใช้กำหนดความกว้างที่มองเห็นได้ในหน่วย **ตัวอักษร (characters)** ไม่ใช่พิกเซล

ความแตกต่าง size vs width vs CSS

วิธี หน่วย พฤติกรรม
size="20" ตัวอักษร (ประมาณ) ขึ้นอยู่กับ font-family และ font-size
width="200" พิกเซล เฉพาะ input type=image เท่านั้น
CSS width: 200px พิกเซล/% แม่นยำที่สุด ควบคุมได้ดีที่สุด
CSS width: 20ch ตัวอักษร (ch unit) แม่นยำกว่า size attribute (1ch = ความกว้างของ '0')

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <style>
    .demo-input { margin: 8px 0; display: block; }
    .fixed-ch { width: 20ch; border: 2px solid blue; }
    .fixed-px { width: 200px; border: 2px solid green; }
    .size-attr { border: 2px solid red; }
  </style>
</head>
<body>
  <h2>เปรียบเทียบวิธีกำหนดความกว้าง input</h2>
  
  <label>size="20" (attribute):</label>
  <input type="text" class="demo-input size-attr" size="20" value="12345678901234567890">
  
  <label>width: 20ch (CSS - แนะนำ):</label>
  <input type="text" class="demo-input fixed-ch" value="12345678901234567890">
  
  <label>width: 200px (CSS):</label>
  <input type="text" class="demo-input fixed-px" value="12345678901234567890">
  
  <hr>
  
  <h3>ตัวอย่างฟอร์มจริง</h3>
  <form action="">
    <label>รหัสสินค้า (4 ตัวอักษร):</label>
    <input type="text" name="sku" size="4" maxlength="4" pattern="[A-Z0-9]{4}" title="4 ตัวอักษร A-Z หรือ 0-9">
    <br><br>
    <label>อีเมล:</label>
    <input type="email" name="email" size="30">
    <br><br>
    <input type="submit" value="ส่งข้อมูล">
  </form>
</body>
</html>

แอตทริบิวต์ที่เกี่ยวข้อง

  • maxlength - จำนวนตัวอักษรสูงสุดที่พิมพ์ได้
  • minlength - จำนวนตัวอักษรขั้นต่ำ (สำหรับ validation)
  • pattern - regex pattern สำหรับ validation

แนวทางปฏิบัติสมัยใหม่

แนะนำ: ใช้ CSS width: Xch แทน size attribute เพราะ:
  • แม่นยำกว่า (1ch = ความกว้างของตัวเลข 0)
  • แยก structure (HTML) และ presentation (CSS)
  • รองรับ responsive design ด้วย media queries
  • ควบคุมได้ละเอียดกว่า (padding, border, box-sizing)

สรุป

size ใช้ได้สำหรับ prototype เร็วๆ หรือฟอร์มง่ายๆ แต่สำหรับ production ควรใช้ CSS เพื่อความควบคุมและความสม่ำเสมอ