如何用 CSS 建立“卡片”?


在網頁上,我們可以輕鬆建立一張卡片,就像你可能在團隊頁面上看到的那樣。員工姓名和職稱會在縮圖中顯示。使用 CSS,我們可以輕鬆建立一張卡片,還可以使用 :hover 選擇器設定懸停樣式。

設定卡片影像

<img> 元素用於設定卡片的影像。將其放在一個 div 中 −

<div class="card">
   <img src="https://tutorialspoint.tw/assets/profiles/123055/profile/200_187394-1565938756.jpg">
   <div class="designation">
      <h3>Amit Diwan</h3>
      <p>Founder</p>
   </div>
</div>

設定卡片標題和文字

在上述 <div> 下,建立另一個 <div> 來設定卡片標題和文字 −

<div class="Designation">
   <h3>Amit Diwan</h3>
   <p>Founder</p>
</div>

設定卡片樣式

我們將上述為卡片設定的 div 設定樣式,使其看起來更專業。為此,我們使用了 box-shadow 屬性。另外還設定 max-width 來設定精確的寬度 −

.card {
	box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
	width: 40%;
	max-width: 300px;
	background-color: rgb(56, 185, 185);
}

滑鼠懸停

將滑鼠懸停在卡片上時,會設定一個略有不同的陰影樣式 −

.card:hover {
   box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
}

設定卡片標題和文字樣式

我們還設定了卡片標題和文字的樣式,使其看起來更專業 −

.designation {
	padding: 2px 16px;
	background-color: rgb(107, 43, 167);
	color:white;
}

示例

要使用 CSS 建立卡片,程式碼如下 −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <style>
      body{
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         margin:20px;
      }
      .card {
         box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
         width: 40%;
         max-width: 300px;
         background-color: rgb(56, 185, 185);
      }
      .card:hover {
         box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
      }
      .designation {
         padding: 2px 16px;
         background-color: rgb(107, 43, 167);
         color:white;
      }
      .card img{
         width: 288px;
         height: 250px;
      }
   </style>
</head>
<body>
   <h1>Card Example</h1>
   <div class="card">
      <img src="https://tutorialspoint.tw/assets/profiles/123055/profile/200_187394-1565938756.jpg">
      <div class="designation">
         <h3>Amit Diwan</h3>
         <p>Founder</p>
      </div>
   </div>
</body>
</html>

更新於: 2023-11-17

303 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告