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

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

คุณสมบัติ display: inline ทำให้ element แสดงในบรรทัดเดียวกัน (ไม่ขึ้นบรรทัดใหม่) และใช้ความกว้าง/สูงเพียงพอต่อเนื้อหา ไม่สามารถกำหนด width/height ได้

ตัวอย่างที่ 1: span แบบ inline

<!DOCTYPE html> <html> <head> <style> span {    background-color: orange;    color: white; } p.demo {    display: none; } span.demo1 {    display: inline; } </style> </head> <body> <h1>Match Details</h1> <div> Match will begin at <p class="demo">9AM</p> 10AM on 20th December. </div> <div> Match will end at <span class="demo1">5PM</span> on 20th December. </div> </body> </html>

ตัวอย่างที่ 2: span พร้อม ID

<!DOCTYPE html> <html> <head> <style> span#demo {    background-color:orange;    color: white;    display:inline; } </style> </head> <body> <h1>Match Details</h1> <div> Match will begin at <span id="demo">9AM</span> on 20th December. </div> </body> </html>

คำอธิบาย

ตัวอย่างทั้งสองแสดง <span> (ซึ่งเป็น inline โดยค่าเริ่มต้น) ใช้ display: inline อย่างชัดเจน ทำให้ "9AM" และ "5PM" แสดงต่อเนื่องกับข้อความรอบๆ

ลักษณะของ Inline Elements:

ลักษณะคำอธิบาย
ขึ้นบรรทัดใหม่ไม่
กำหนด width/heightไม่ได้
margin/padding แนวตั้งไม่ส่งผลต่อ layout (แต่สร้าง visual space ได้)
margin/padding แนวนอนทำงานปกติ
text-alignต้องตั้งที่ parent block
vertical-alignทำงานได้ (baseline, top, middle, bottom)

Inline Elements มาตรฐาน:

<span>, <a>, <strong>, <em>, <img>, <input>, <button>, <label>, <select>, <br>

เปรียบเทียบ Inline vs Inline-block vs Block:

คุณสมบัติinlineinline-blockblock
ขึ้นบรรทัดใหม่ไม่ไม่ใช่
width/heightไม่ได้ได้ได้
margin แนวตั้งไม่มีผลได้ได้
padding แนวตั้งvisual onlyได้ได้