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

การจัดสไตล์ปุ่มดาวน์โหลดด้วย CSS

สร้างปุ่มดาวน์โหลด (Download Buttons) ที่สวยงาม ด้วย CSS และ Font Awesome Icons

ตัวอย่างโค้ด

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> button{    background-color: rgb(78, 15, 129);    border: none;    color: white;    padding: 12px 30px;    cursor: pointer;    font-size: 30px;    font-weight: bolder;    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } button:hover{    background-color: rgb(42, 7, 82); } h1{    text-align: center; } </style> </head> <body> <h1>Download Buttons Styling Example</h1> <h1>Button 1</h1> <button style="margin-left:33%;"><i class="fa fa-download"></i> DOWNLOAD NOW</button> <h1>Button 2</h1> <button style="text-align: center; width: 100%;"><i class="fa fa-download"></i> DOWNLOAD NOW</button> </body> </html>

คำอธิบาย

ปุ่ม 1: ใช้ margin-left: 33% จัดกึ่งกลางคร่าวๆ ปุ่ม 2: width: 100% กว้างเต็ม container ทั้งคู่ใช้ Font Awesome fa-download icon

เวอร์ชันปรับปรุง (Modern & Reusable):

CSS Classes แทน Inline Styles:

.btn-download {
  display: inline-flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 2rem;
  background: #4e0f81;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.125rem;
  font-weight: 700;
  font-family: system-ui, sans-serif;
  cursor: pointer;
  transition: background 0.2s, transform 0.1s;
}
.btn-download:hover { background: #2a0752; }
.btn-download:active { transform: scale(0.98); }
.btn-download:focus-visible { outline: 3px solid #4e0f81; outline-offset: 3px; }

.btn-download--full { width: 100%; }
.btn-download--center { margin: 0 auto; display: flex; justify-content: center; }

HTML:

<button class="btn-download">
  <svg class="icon" aria-hidden="true">...</svg>
  Download Now
</button>

<button class="btn-download btn-download--full">
  <svg class="icon" aria-hidden="true">...</svg>
  Download Now
</button>

Icon แนะนำ: ใช้ SVG แทน Font Awesome:

<svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
  <polyline points="7 10 12 15 17 10"></polyline>
  <line x1="12" y1="15" x2="12" y2="3"></line>
</svg>

Accessibility:

  • ใช้ <button> ไม่ใช่ <a> (ถ้าไม่ได้ link ไปหน้าอื่น)
  • Icon ใส่ aria-hidden="true" (ข้อความในปุ่มบอกความหมายแล้ว)
  • มี :focus-visible สำหรับ keyboard navigation
  • เพิ่ม aria-busy="true" + loading spinner ระหว่างดาวน์โหลด

Variants:

.btn-download--secondary { background: white; color: #4e0f81; border: 2px solid #4e0f81; }
.btn-download--ghost { background: transparent; color: #4e0f81; border: 2px solid transparent; }
.btn-download--ghost:hover { background: rgba(78,15,129,0.1); }