如何使用 CSS 建立產品卡片?


在電子商務網站上,您一定見過針對特定產品的卡片。其中包括產品名稱、圖片、價格、任何折扣等等。在網頁上,我們可以輕鬆地使用 CSS 建立產品卡片。在此基礎上,購買或新增至購物車按鈕可置於此卡中,以便使用者直接購買產品。

設定卡片的 div

在產品卡片的 div 下,將產品圖片和產品名稱設定為標題。另外,將產品詳細資訊和價格置於 <p> 元素中。此外,使用 <button> 元素來設定購買按鈕:

<div class="productCard">
   <img src="https://images.pexels.com/photos/1152077/pexels-photo-1152077.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="width:100%"/>
   <h1>Leather Bag</h1>
   <p class="productDetails">Exotic Quality</p>
   <p>Price 50$</p>
   <p><button>Buy Now</button></p>
</div>

設定卡片樣式

若要設定產品卡片的樣式,請使用 max-width 屬性設定最大寬度。使用 text-align 屬性將卡片的文字對齊到中心。另外,設定 box shadow:

.productCard {
   box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
   max-width: 300px;
   margin: auto;
   text-align: center;
   font-family: arial;
   background-color: rgb(190, 224, 224);
}

產品卡片詳細資訊

賦予詳細資訊不同的外觀,使其看起來更具吸引力。可以使用 font-weight 屬性設定字型樣式:

.productDetails {
   color: rgb(26, 0, 51);
   font-weight: bold;
   font-size: 18px;
}

顯示按鈕

產品卡片上的按鈕使用 display 屬性進行顯示,值設定為 inline-block。將 cursor 屬性設定為 pointer,以便使游標看起來可點選:

button {
   border: none;
   outline: 0;
   display: inline-block;
   padding: 8px;
   color: white;
   background-color: rgb(23, 31, 102);
   text-align: center;
   cursor: pointer;
   width: 100%;
   font-size: 18px;
}

示例

若要使用 CSS 建立產品卡片,程式碼如下:

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .productCard {
         box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
         max-width: 300px;
         margin: auto;
         text-align: center;
         font-family: arial;
         background-color: rgb(190, 224, 224);
      }
      .productDetails {
         color: rgb(26, 0, 51);
         font-weight: bold;
         font-size: 18px;
      }
      button {
         border: none;
         outline: 0;
         display: inline-block;
         padding: 8px;
         color: white;
         background-color: rgb(23, 31, 102);
         text-align: center;
         cursor: pointer;
         width: 100%;
         font-size: 18px;
      }
      button:hover, a:hover {
         opacity: 0.7;
      }
   </style>
</head>
<body>
   <h2 style="text-align:center">Product Card Example</h2>
   <div class="productCard">
      <img src="https://images.pexels.com/photos/1152077/pexels-photo-1152077.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="width:100%"/>
      <h1>Leather Bag</h1>
      <p class="productDetails">Exotic Quality</p>
      <p>Price 50$</p>
      <p><button>Buy Now</button></p>
   </div>
</body>
</html>

更新時間:2023 年 12 月 8 日

996 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.