How to create a card component with image in CSS

Last Updated on Dec 01, 2023

shoe product card

In my previous post, I talked about how to create a simple card component in CSS. In this blog, we will use the same card and add an image.

A card with an image can be seen on a lot of websites. It can be used to create a product card, a profile card, a blog post card, and so on.

Without further delay, let's get started.

  1. Create the neccessary files

    In the folder of your choice, create the following files: index.html and style.css. In addition, prepare the image that you will use. If you want to use the image that I used, you can download it here.

  2. Create the HTML card

    Type the following code in index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>How to create a card component with image in CSS</title>
        <link rel="stylesheet" href="style.css">
      </head>
      <body>
        <div class="card w-25 mx-auto">
        <img src="pexels-web-donut-19090.jpg" alt="blue shoe" class="img-fluid">
          <div class="card-body">
            <h2>Product Name</h2>
            <p class="price">₱2000</p>
            <button class="btn btn-add-cart">Add to cart</button>
          </div>
        </div>
      </body>
    </html>
    

    Just like in my previous post, our card starts with the a container that has a class card. Inside the container, we have our image and container with a class card-body.

  3. Style the card with CSS

    Type the following code in style.css

    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    body {
      background-color: hsl(0, 0%, 92%);
      padding: 10px;
    }
    .card {
      border: 1px solid hsl(0, 0%, 80%);
      background-color: white;
      border-radius: 10px;
      overflow: hidden;
    }
    .card-body {
      padding: 16px;
    }
    .w-25 {
      width: 25%;
    }
    .mx-auto {
      margin-left: auto;
      margin-right: auto;
    }
    .img-fluid {
      width: 100%;
    }
    .price {
      margin: 16px 0;
      font-size: 20px;
    }
    .btn {
      display: inline-block;
      padding: 12px 14px;
      border-radius: 5px;
      border: none;
      cursor: pointer;
    }
    .btn-add-cart {
      background-color: hsl(0, 100%, 45%);
      color: white;
    }
    

    With a combination of border, background-color, border-radius, and overflow set to hidden, we can have a card.

    By setting the width of image to 100%, the image will cover the card's width and adjust its height automatically since the default value of image's height is auto.

Summary

In this tutorial, we have created a card component with image using HTML and CSS.

© John Michael Balbarona