Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo hình ảnh thu nhỏ (thumbnail) với CSS

Thumbnail image với border + padding

Thumbnail thường có: **viền mỏng, padding nhỏ, bo góc nhẹ, hover effect**. Dùng `border`, `padding`, `border-radius`, `transition`.

Ví dụ cơ bản

<!DOCTYPE html>
<html>
<head>
  <style>
    img {
      border: 2px solid orange;
      border-radius: 3px;
      padding: 7px;
      background: white;        /* Nền cho padding area */
      transition: transform 0.2s, box-shadow 0.2s;
    }
    img:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    }
  </style>
</head>
<body>
  <img src="coding_ground_home.jpg" alt="Online Compiler" width="300" height="300">
</body>
</html>

Thiết kế Thumbnail Card (Phổ biến hơn)

<!DOCTYPE html>
<html>
<head>
  <style>
    .thumbnail {
      display: inline-block;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;         /* Quan trọng: cắt bo góc ảnh bên trong */
      background: white;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      transition: box-shadow 0.3s, transform 0.3s;
    }
    .thumbnail:hover {
      box-shadow: 0 8px 24px rgba(0,0,0,0.15);
      transform: translateY(-2px);
    }
    .thumbnail img {
      display: block;           /* Loại bỏ gap dưới ảnh */
      width: 100%;
      height: auto;
    }
    .thumbnail-caption {
      padding: 12px;
      font-size: 14px;
      color: #333;
    }
  </style>
</head>
<body>
  <div class="thumbnail">
    <img src="image.jpg" alt="Mô tả ảnh">
    <div class="thumbnail-caption">Caption ở đây</div>
  </div>
</body>
</html>

Responsive Thumbnail Grid

.thumbnail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}
@media (max-width: 600px) {
  .thumbnail-grid { grid-template-columns: 1fr; }
}

Lưu ý quan trọng

  • display: block trên img loại bỏ khoảng trắng dưới ảnh (baseline alignment).
  • overflow: hidden trên container bắt buộc khi có border-radius.
  • object-fit: cover nếu ảnh tỷ lệ khác container.
  • Dùng loading="lazy" trên `` cho performance.