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

การสร้าง Icon Bar ด้วย CSS

สร้าง Icon Bar (แถบไอคอน) ด้วย CSS สำหรับ navigation หรือ toolbar

ตัวอย่างที่ 1: Horizontal Icon Bar

<!DOCTYPE html> <html> <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> .icon-bar {    width: 100%;    background-color: black;    overflow: auto; } .icon-bar a {    float: left;    width: 30%;    text-align: center;    color: white;    font-size: 30px; } .active {    background-color: blue; } </style> <body>    <div class="icon-bar">       <a href="#"><i class="fa fa-home"></i></a>       <a href="#"><i class="fa fa-search"></i></a>       <a class="active" href="#"><i class="fa fa-bars"></i></a>    </div> </body> </html>

ตัวอย่างที่ 2: Vertical Icon Bar

<!DOCTYPE html> <html> <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> .icon-bar {    width: 50px;    background-color: black; } .icon-bar a {    display: block;    text-align: center;    color: white;    font-size: 30px; } .active {    background-color: blue; } </style> <body>    <div class="icon-bar">       <a class="active" href="#"><i class="fa fa-home"></i></a>       <a href="#"><i class="fa fa-search"></i></a>       <a href="#"><i class="fa fa-bars"></i></a>    </div> </body> </html>

คำอธิบาย

ตัวอย่างที่ 1: แนวนอน (Horizontal) ใช้ float: left และ width: 30% ตัวอย่างที่ 2: แนวตั้ง (Vertical) ใช้ display: block และ width: 50px คลาส .active ไฮไลต์ไอคอนที่เลือก

เวอร์ชันสมัยใหม่ (Modern CSS - Flexbox):

Horizontal:

.icon-bar {
  display: flex;
  background: black;
}
.icon-bar a {
  flex: 1;
  text-align: center;
  color: white;
  font-size: 1.5rem;
  padding: 1rem;
  text-decoration: none;
}
.icon-bar a.active { background: blue; }
.icon-bar a:hover { background: #333; }

Vertical:

.icon-bar {
  display: flex;
  flex-direction: column;
  width: 60px;
  background: black;
}
.icon-bar a { /* เหมือน horizontal */ }

ใช้ SVG Icons แทน Font Awesome (แนะนำ):

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
  <polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>

ข้อดี: ไม่ต้องโหลด font ใหญ่, scalable, 可控制สีด้วย currentColor, accessible