Attributes

#HelloFront-end #HelloErmine #HelloWorld2021

ตัวอย่างของ Attributes

  • href เป็น attribute ของ <a>ใช้กำหนด URL ของหน้าเว็บไซต์หรือเว็บเพจที่เราต้องการ link ไปหา

  • src เป็น attribute ของ <img> จะเป็นการกำหนด path ของไฟล์รูปภาพเพื่อที่จะดึงภาพมาใช้

  • width และ height เป็น attribute ของ <img> ใช้กำหนดความกว้างเเละความสูงของรูปภาพ

  • alt เป็น attribute ของ <img> ใช้กำหนดคำอธิบายเพิ่มเติมให้รูปภาพในกรณีที่รูปภาพไม่แสดงผลบนหน้าเว็บเพจ

  • style เป็น attribute ที่ใช้เพื่อกำหนดรายละเอียดคุณลักษณะเพิ่มเติมต่าง ๆ ในเเต่ละ element เช่น สี ขนาดตัวอักษร ฯลฯ

  • title เป็น attribute ที่ใช้กำหนดหรือนิยามข้อมูลเพิ่มเติมหรือข้อมูลเฉพาะให้กับ element

Class Attribute

เป็น attribute สำหรับใช้ระบุ class ให้กับ HTML element โดย 1 class สามารถนำไปใช้ได้กับหลาย ๆ element (class ใช้ได้ทั่วถึง) โดยการระบุ class ทำเมื่อเราต้องการให้คุณลักษณะชุดหนึ่ง เกิดขึ้นกับ element หลาย ๆ ตำแหน่ง

ตัวอย่าง เราได้ทำการสร้าง class และกำหนดคุณลักษณะต่าง ๆ ไว้ภายใต้ <style> ซึ่งถูกเขียนไว้ใน <head> อีกที โดย class ของเรามีชื่อว่า city สิ่งที่ใช้บอกว่ามันเป็น class คือการใส่เครื่องหมายจุด (.) ไว้นำหน้าชื่อ หลังจากกำหนดคุณลักษณะให้ class แล้ว เราก็นำชื่อ class นี้ไปกำหนดให้ class attribute ในทุก element ที่เราต้องการให้แสดงคุณลักษณะชุดเดียวกัน

<!DOCTYPE html>
<html>
<head>
<style>
.city {
  background-color: tomato;
  color: white;
  border: 2px solid black;
  margin: 20px;
  padding: 20px;
}
</style>
</head>
<body>

<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div> 

<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>

<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>

</body>
</html>

ผลลัพธ์

ที่มาของ code และผลลัพธ์ : https://www.w3schools.com/html/tryit.asp?filename=tryhtml_classes_capitals

Id Attribute

เป็น attribute สำหรับใช้ระบุ id เฉพาะให้ HTML element โดย 1 id ใช้ได้ต่อ 1 element เท่านั้น โดยการระบุ id ทำเมื่อเราต้องการให้คุณลักษณะชุดหนึ่ง เกิดขึ้นกับ element หนึ่ง โดยไม่กระทบ element อื่น ๆ ที่มีการใช้ tag เหมือนกัน

ตัวอย่าง เราได้ทำการสร้าง id และกำหนดคุณลักษณะต่าง ๆ ไว้ภายใต้ <style> ซึ่งถูกเขียนไว้ใน <head> อีกทีโดย id ของเรามีชื่อว่า myHeader สิ่งที่ใช้บอกว่ามันเป็น id คือการใส่เครื่องหมายชาร์ป (#) ไว้นำหน้าชื่อ หลังจากกำหนดคุณลักษณะให้ id แล้ว เราก็นำชื่อ id นี้ไปกำหนดให้ id attribute ใน element header (ในที่นี้ใช้กับ <h1>) ซึ่งเราจะเห็นว่ามี <h1> อยู่ 2 อัน แต่เราอยากให้มันปรากฏที่ตำแหน่งเดียวโดยไม่กระทบกับ <h1> อีกอัน จึงใช้ id

<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
  background-color: lightblue;
  color: blue;
  padding: 40px;
  text-align: center;
}
h2 {
    color:red;
}
</style>
</head>
<body>

<h1>The id Attribute </h1>
<h2>Use CSS to style an element with the id "myHeader":</h2>

<h1 id="myHeader">My Header</h1>
<h2> My Another Head</h2>

</body>
</html>

ผลลัพธ์

ที่มาของ code และผลลัพธ์บางส่วน : https://www.w3schools.com/html/tryit.asp?filename=tryhtml_id_css

Last updated

Was this helpful?