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

การแสดงผลแบบ Block ด้วย CSS display: block

คุณสมบัติ display: block ทำให้ element แสดงผลแบบ block-level เริ่มบรรทัดใหม่ และกว้างเต็มพื้นที่ container (available width)

ตัวอย่างที่ 1: แปลง <p> (block by default) ให้ชัดเจน + inline-block

<!DOCTYPE html>
<html>
<head>
  <style>
    p { background-color: orange; color: white; }
    p.demo1 { display: block; }
    p.demo2 { display: inline-block; }
  </style>
</head>
<body>
  <h1>Match Details</h1>
  <div> 
    Match will begin at <p class="demo1">10AM</p> on 19th December, 2019. 
  </div>
  <hr />
  <div> 
    Match will end at <p class="demo2">5PM</p> on 19th December, 2019. 
  </div>
</body>
</html>

คำอธิบาย: p.demo1 เป็น block เริ่มบรรทัดใหม่ กว้างเต็ม ทำให้ "on 19th..." ตกบรรทัดใหม่ p.demo2 เป็น inline-block อยู่ในบรรทัดเดียวกับข้อความรอบๆ แต่กำหนด width/height ได้

ตัวอย่างที่ 2: Block element ในกลางประโยค

<!DOCTYPE html>
<html>
<head>
  <style>
    p { background-color: orange; color: white; }
    p.demo { display: block; }
  </style>
</head>
<body>
  <h1>Student Result</h1>
  <div> 
    The result of MCA student will be declared on <p class="demo">20th December 2019</p>Check the website on the same day at 8PM. 
  </div>
</body>
</html>

Display Values หลัก

ค่าพฤติกรรมตัวอย่าง Element
blockบรรทัดใหม่, กว้างเต็ม, มี width/height/margin ได้div, p, h1-h6, section, header, footer
inlineอยู่ในบรรทัดเดียว, ไม่มี width/height/margin top/bottomspan, a, strong, em, img
inline-blockอยู่ในบรรทัดเดียว, มี width/height/margin ได้button, input, custom elements
flexFlex containerlayout containers
gridGrid containerlayout containers
noneไม่แสดงผลเลย (ลบออกจาก layout)-

การประยุกต์: ใช้ display: block เพื่อทำให้ inline element (เช่น <a>, <span>) มีพื้นที่คลิกกว้างขึ้น หรือจัด layout แนวตั้ง