สร้างกลุ่มปุ่มแนวนอน (Horizontal Button Group) ปุ่มติดกันไม่มีช่องว่าง ใช้ float: left และ border-right คั่นระหว่างปุ่ม
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <style> .btnGroup{ display: inline-block; font-size: 0; border: 2px solid darkgreen; box-shadow: 5px 10px 18px rgb(55, 173, 39); } button{ float: left; margin:0px; border:none; padding: 15px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-weight: bold; font-size: 20px; } button:not(:last-child){ border-right: 2px solid rgb(6, 134, 49); } button:hover{ background:rgb(48, 24, 134); box-shadow: 5px 10px 18px rgb(41, 39, 173); color:white; } </style> <body> <h1>Button Group</h1> <div class="btnGroup"> <button>Facebook</button> <button>Twitter</button> <button>LinkedIn</button> </div> <h2>Hover over the above button group to see hover effects</h2> </body> </html>
ความแตกต่างจาก Vertical
- button { float: left; } - เรียงแนวนอน (แทน display: block)
- button:not(:last-child) { border-right: ... } - เส้นคั่นแนวตั้ง (แทน border-bottom)
- Container ใช้
display: inline-blockจัดกลางได้ด้วยtext-align: centerบน Parent
วิธีทันสมัยกว่า (Flexbox)
.btnGroup { display: flex; border: 2px solid darkgreen; }
button { flex: 1; border: none; border-right: 2px solid rgb(6,134,49); }
button:last-child { border-right: none; }
Flexbox จัดการช่องว่างและความกว้างอัตโนมัติ ไม่ต้อง font-size: 0
ผลลัพธ์
กลุ่มปุ่ม 3 ปุ่มติดกันแนวนอน ขอบเขียว Hover -> สีม่วงเงาแก้วน้ำเงิน ตัวอักษรขาว