Modern Ecommerce Product Card using HTML, Tailwind & JS

Faraz

By Faraz -

Learn how to create a modern ecommerce product card using HTML, TailwindCSS, and JavaScript with simple steps for beginners.


modern-ecommerce-product-card-using-html-tailwind-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

An e-commerce product card is one of the most important parts of an online shopping website. A product card usually displays product images, name, price, rating, and a call-to-action button like “Add to Cart” or “Buy Now.”

In this tutorial, you will learn how to create a modern and responsive e-commerce product card using HTML, TailwindCSS, and JavaScript. The design will be clean, user-friendly, and fully responsive for all devices.

Prerequisites

Before starting, make sure you have:

  • Basic knowledge of HTML
  • Basic understanding of CSS / TailwindCSS
  • A text editor like VS Code
  • Browser (Chrome/Edge/Firefox) to test the code

Source Code

Step 1 (HTML Code):

To get started, we first need to create a basic HTML file. In this file, we will include the main structure for our product card. Let's break down the HTML code step by step:

1. Header Section (<head>)

  • <!DOCTYPE html> → Declares HTML5 document type.
  • <html lang="en"> → Webpage language is English.
  • <meta charset="UTF-8"> → Supports all character sets (Unicode).
  • <meta name="viewport" ...> → Makes page responsive for mobile devices.
  • <title> → Title shown in the browser tab.
  • Tailwind CSS → Loaded via CDN for utility-based styling.
  • Tailwind Config → Enables dark mode using the class method.
  • Google Fonts (Inter) → Adds modern, clean typography.
  • FontAwesome → Provides icons (stars, robot, moon, sun, etc.).
  • styles.css → Custom CSS file (for extra styling not covered by Tailwind).

2. Body Section (<body>)

The whole page is wrapped inside:

<div class="container mx-auto p-8 flex justify-center min-h-screen items-center">
  • This centers everything on the page with padding.

3. Theme Switcher (Light/Dark Mode)

<div class="fixed top-4 right-4 ...">
   <button onclick="setTheme('light')">☀️</button>
   <button onclick="setTheme('dark')">🌙</button>
</div>
  • User can toggle between light 🌞 and dark 🌙 theme.

4. Product Card

<div class="card-hover w-full max-w-md rounded-2xl ...">
  • This is the main product card that contains:
  • AI Badge (🤖 AI-PERSONALIZED) → Shows that the product is AI-recommended.
  • Product Image (Sneakers) with:
  • Rotate & Expand buttons (3D/zoom controls).
  • AR Preview button (for trying via Augmented Reality).

5. Product Info

Inside <div class="p-6">:

  • Product Name → QuantumX Sneakers
  • Description → Next-gen smart footwear
  • Price → Old price ($199.99) + Discounted price ($159.99)
  • Rating → ⭐ 4.8 (with reviews).

6. AI Recommendations

<p>AI recommends: Perfect for your active lifestyle</p>
<p>95% match with your preferences</p>
<p>Top feature: Adaptive cushioning with AI</p>
  • This shows personalized AI suggestions for the customer.

7. AI Feature Chips

<div class="ai-chip">⚡ Self-lacing</div>
<div class="ai-chip">❤️ Health tracking</div>
<div class="ai-chip">🔋 7-day battery</div>
  • Small pill-shaped tags describing features.

8. Voice Interaction

<button id="voiceButton">🎤</button>
<p>Ask AI: "How do these compare to Nike Adapt?"</p>
  • Let's users ask questions with voice.

9. AI Suggested Products

AI ALSO SUGGESTS:
🧦 Smart Socks | 👕 Performance Shirt | ⏰ Fitness Tracker
  • Hover shows tooltips, like a mini recommendation system.

10. Action Buttons

<button>❤️ Save</button>
<button>⚡ Buy Now</button>
  • For wishlist & purchase.

11. AI Shopping Assistant

<div id="aiAssistant">🤖</div>
  • A floating robot icon in the corner.
  • On hover, tooltip → AI Shopping Assistant.

12. AI Response Modal

<div id="aiResponseModal" class="hidden">
   <h3>AI Assistant</h3>
   <p id="aiResponseText"></p>
   <button>Show Comparison</button>
   <button>More Details</button>
   <button>❌</button>
</div>
  • Hidden pop-up modal that appears when the AI Assistant is clicked.
  • Displays AI-generated responses.
  • Includes action buttons.

13. JavaScript

<script src="script.js"></script>
  • Handles theme switching, modal open/close, voice interactions, etc.

Step 2 (CSS Code):

Once the basic HTML structure of the product card is in place, the next step is to add styling to the card using CSS. Let's break down the CSS code step by step:

1. Theme Variables (.light & .dark)

These define CSS custom properties (variables) for light mode and dark mode.

.light {
  --bg-color: #f9fafb;
  --card-bg: #ffffff;
  --text-primary: #111827;
  --text-secondary: #6b7280;
  --border-color: #e5e7eb;
  --accent-color: #3b82f6;
  --shadow-color: rgba(0, 0, 0, 0.1);
  --highlight-color: #eff6ff;
  --badge-gradient: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%);
  --chip-bg: #f3f4f6;
}
  • Sets light theme colors (white backgrounds, dark text).
.dark {
  --bg-color: #111827;
  --card-bg: #1f2937;
  --text-primary: #f9fafb;
  --text-secondary: #9ca3af;
  --border-color: #374151;
  --accent-color: #60a5fa;
  --shadow-color: rgba(255, 255, 255, 0.05);
  --highlight-color: #1e3a8a;
  --badge-gradient: linear-gradient(135deg, #1e40af 0%, #0369a1 100%);
  --chip-bg: #4b5563;
}
  • Sets dark theme colors (dark background, light text).

So when the body has class="light" or class="dark", it switches all variables.

2. Base Styles

body {
  background-color: var(--bg-color);
  color: var(--text-primary);
  font-family: 'Inter', sans-serif;
  transition: background-color 0.5s ease, color 0.3s ease;
}
  • Background & text color come from theme variables.
  • Smooth transition when switching themes.

3. Product Card & Utility Classes

.product-card { background-color: var(--card-bg); border-color: var(--border-color); color: var(--text-primary); }
.text-primary { color: var(--text-primary); }
.text-secondary { color: var(--text-secondary); }
.bg-highlight { background-color: var(--highlight-color); }
.bg-chip { background-color: var(--chip-bg); }
.border-primary { border-color: var(--border-color); }
.bg-accent { background-color: var(--accent-color); }
  • These classes pull values from the theme variables to ensure consistent light/dark styles.

4. Animations (Keyframes)

Pulse Animation (for AI badge)

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}
.ai-pulse { animation: pulse 2s infinite; }
  • Makes elements fade in & out slowly (used on 🤖 AI badge).

Float Animation (for 3D/hover effects)

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-8px); }
  100% { transform: translateY(0px); }
}
.float-animation { animation: float 6s ease-in-out infinite; }
  • Makes elements gently float up & down.

Voice Pulse (Microphone Effect)

@keyframes voicePulse {
  0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); }
  100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
}
.voice-pulse { animation: voicePulse 1.5s infinite; }
  • Creates a radiating wave effect around the voice button.

Fade-In

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in { animation: fadeIn 0.3s ease-out forwards; }
  • Smooth slide + fade when modals appear.

5. Transitions & Hover Effects

.theme-switch { transition: all 0.5s cubic-bezier(0.22, 1, 0.36, 1); }
.card-hover { transition: all 0.3s cubic-bezier(0.22, 1, 0.36, 1); }
.card-hover:hover { transform: translateY(-4px); }
  • Buttons and cards move smoothly on hover.
.ai-chip { transition: all 0.3s ease; }
.ai-chip:hover {
  transform: scale(1.05);
  background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%);
}
  • Feature chips grow & get a gradient background on hover.
.product-badge { transition: all 0.3s ease; }
.product-badge:hover { transform: translateY(-2px); }
  • AI badge lifts slightly on hover.

6. Utility

.hidden { display: none; }
  • Used to hide modal or other elements dynamically with JavaScript.


.light {
  --bg-color: #f9fafb;
  --card-bg: #ffffff;
  --text-primary: #111827;
  --text-secondary: #6b7280;
  --border-color: #e5e7eb;
  --accent-color: #3b82f6;
  --shadow-color: rgba(0, 0, 0, 0.1);
  --highlight-color: #eff6ff;
  --badge-gradient: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%);
  --chip-bg: #f3f4f6;
}

.dark {
  --bg-color: #111827;
  --card-bg: #1f2937;
  --text-primary: #f9fafb;
  --text-secondary: #9ca3af;
  --border-color: #374151;
  --accent-color: #60a5fa;
  --shadow-color: rgba(255, 255, 255, 0.05);
  --highlight-color: #1e3a8a;
  --badge-gradient: linear-gradient(135deg, #1e40af 0%, #0369a1 100%);
  --chip-bg: #4b5563;
}

body {
  background-color: var(--bg-color);
  color: var(--text-primary);
  font-family: 'Inter', sans-serif;
  transition: background-color 0.5s ease, color 0.3s ease;
}

.product-card {
  background-color: var(--card-bg);
  border-color: var(--border-color);
  color: var(--text-primary);
}

.text-primary {
  color: var(--text-primary);
}

.text-secondary {
  color: var(--text-secondary);
}

.bg-highlight {
  background-color: var(--highlight-color);
}

.bg-chip {
  background-color: var(--chip-bg);
}

.border-primary {
  border-color: var(--border-color);
}

.bg-accent {
  background-color: var(--accent-color);
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}
@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-8px);
  }
  100% {
    transform: translateY(0px);
  }
}
@keyframes voicePulse {
  0% {
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.ai-pulse {
  animation: pulse 2s infinite;
}
.float-animation {
  animation: float 6s ease-in-out infinite;
}
.voice-pulse {
  animation: voicePulse 1.5s infinite;
}
.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}
.theme-switch {
  transition: all 0.5s cubic-bezier(0.22, 1, 0.36, 1);
}
.ai-chip {
  transition: all 0.3s ease;
}
.ai-chip:hover {
  transform: scale(1.05);
  background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%);
}
.product-badge {
  transition: all 0.3s ease;
}
.product-badge:hover {
  transform: translateY(-2px);
}
.hidden {
  display: none;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let's break down the JS code step by step:

1. DOM Elements

At the top, it grabs references to elements in the HTML by their id.

const voiceButton = document.getElementById('voiceButton');

This means the script is expecting buttons/modals in the HTML with IDs like voiceButton, rotateBtn, etc.

2. State Variables

  • It keeps track of UI states with variables:
  • isRotating → is the product image spinning?
  • rotationInterval → stores interval ID for rotation animation.
  • currentRotation → current Y rotation angle.
  • isExpanded → is the product zoomed in?
  • isSaved → has the product been saved?

3. Theme Switching

function setTheme(theme) { ... }
function loadTheme() { ... }
  • Removes existing theme class (light or dark).
  • Applies the selected theme to <body>.
  • Saves preference in localStorage.
  • Calls updatePersonalization() → updates colors/styles for elements using CSS variables.

This lets the page remember whether the user prefers light mode or dark mode.

4. Modal System (AI Assistant Responses)

function showAIResponse(message, action1Text, action2Text) { ... }
  • Displays a modal with AI’s response text.
  • Dynamically changes the modal action buttons depending on context.
  • First click → “Show Comparison”
  • Next click → “View Full Chart”
  • Then → “Close”
  • This gives a conversational feel.

    5. Voice Button

    voiceButton.addEventListener('click', function () { ... });
    • Adds a spinning animation (pretending to listen).
    • After 2 seconds → replaces with microphone icon.
    • Opens a modal with an AI response about the product.
    • Simulates voice-based product queries.

    6. 3D Rotation

    rotateBtn.addEventListener('click', function () { ... });
    • Toggles product rotation on/off.
    • Uses setInterval() to rotate an <img> element along the Y-axis.

    7. Expand / Zoom

    expandBtn.addEventListener('click', function () { ... });
    • Adds/removes a scale-150 class to the product image.
    • Toggles button icon between expand (fa-expand) and compress (fa-compress).

    8. AR Try-On

    arBtn.addEventListener('click', function () { ... });
    • Opens a modal with a message simulating AR (camera try-on).
      (No real AR code here — just text simulation).

    9. View All Similar Products

    viewAllBtn.addEventListener('click', function () { ... });
    • Shows a modal listing 8 similar products.

    10. Save Product

    saveBtn.addEventListener('click', function () { ... });
    • Toggles between “Saved” ❤️ and “Save” ♡ states.
    • Changes button colors based on the theme.
    • Shows a modal asking if the user wants a price alert.

    11. Buy Product

    buyBtn.addEventListener('click', function () { ... });
    • Shows a modal confirming purchase.
    • Asks if the user wants a 2-year protection plan.

    12. AI Assistant Button

    aiAssistant.addEventListener('click', function () { ... });
    • Opens a modal where AI offers help (comparison, Q&A).

    13. Personalization (Theme-Aware Updates)

    function updatePersonalization() { ... }
    • Updates badge, buttons, borders, highlights, etc. based on current theme.
    • Uses CSS variables (--bg-color, --accent-color, etc.).

    14. Initialization

    document.addEventListener('DOMContentLoaded', function () { ... });
    • Loads saved theme from localStorage.
    • Sets up modal close behavior (click outside modal or press Escape).
    // DOM Elements
    const voiceButton = document.getElementById('voiceButton');
    const rotateBtn = document.getElementById('rotateBtn');
    const expandBtn = document.getElementById('expandBtn');
    const arBtn = document.getElementById('arBtn');
    const viewAllBtn = document.getElementById('viewAllBtn');
    const saveBtn = document.getElementById('saveBtn');
    const buyBtn = document.getElementById('buyBtn');
    const aiAssistant = document.getElementById('aiAssistant');
    const aiResponseModal = document.getElementById('aiResponseModal');
    const aiResponseText = document.getElementById('aiResponseText');
    const modalAction1 = document.getElementById('modalAction1');
    const modalAction2 = document.getElementById('modalAction2');
    
    // Current state
    let isRotating = false;
    let rotationInterval;
    let currentRotation = 0;
    let isExpanded = false;
    let isSaved = false;
    
    // Set theme function - COMPLETELY REWORKED
    function setTheme(theme) {
      // Remove all theme classes first
      document.body.classList.remove('light', 'dark');
      // Add the selected theme class
      document.body.classList.add(theme);
    
      // Update theme in localStorage
      localStorage.setItem('preferredTheme', theme);
    
      updatePersonalization();
    }
    
    // Load preferred theme from localStorage
    function loadTheme() {
      const preferredTheme = localStorage.getItem('preferredTheme') || 'light';
      setTheme(preferredTheme);
    }
    
    // Show modal with AI response
    function showAIResponse(
      message,
      action1Text = 'Show Comparison',
      action2Text = 'More Details'
    ) {
      aiResponseText.textContent = message;
      modalAction1.textContent = action1Text;
      modalAction2.textContent = action2Text;
      aiResponseModal.classList.remove('hidden');
    
      // Set up modal actions based on context
      modalAction1.onclick = function () {
        if (action1Text === 'Show Comparison') {
          showAIResponse(
            "Here's how QuantumX compares to other products:\n\n• More responsive than Nike Adapt\n• Better battery life than Puma Smart\n• More comfortable than Adidas 1.1",
            'View Full Chart',
            'Close'
          );
        } else if (action1Text === 'View Full Chart') {
          showAIResponse(
            'Opening full comparison chart in a new window...',
            'Got it',
            'Close'
          );
        } else {
          closeModal();
        }
      };
    
      modalAction2.onclick = function () {
        if (action2Text === 'More Details') {
          showAIResponse(
            'QuantumX technical details:\n\n• AI-powered adaptive cushioning\n• Self-lacing system\n• Health tracking (steps, gait analysis)\n• 7-day battery life\n• Water resistant',
            'Spec Sheet',
            'Close'
          );
        } else {
          closeModal();
        }
      };
    }
    
    // Close modal
    function closeModal() {
      aiResponseModal.classList.add('hidden');
    }
    
    // Voice button interaction
    voiceButton.addEventListener('click', function () {
      // Prevent multiple clicks
      if (voiceButton.classList.contains('voice-pulse')) return;
    
      voiceButton.classList.add('voice-pulse');
      voiceButton.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i>';
    
      // Simulate voice recognition
      setTimeout(() => {
        voiceButton.classList.remove('voice-pulse');
        voiceButton.innerHTML =
          '<i class="fas fa-microphone"></i><div class="absolute inset-0 rounded-full border-2 border-blue-400 dark:border-blue-300 opacity-0 hover:opacity-100 transition-opacity"></div>';
    
        showAIResponse(
          'The QuantumX sneakers feature more responsive cushioning compared to Nike Adapt, with better battery life for your usage patterns. Would you like me to show a comparison table?'
        );
      }, 2000);
    });
    
    // 3D Rotation functionality
    rotateBtn.addEventListener('click', function () {
      isRotating = !isRotating;
    
      if (isRotating) {
        rotateBtn.innerHTML = '<i class="fas fa-pause text-xs"></i>';
        rotationInterval = setInterval(() => {
          currentRotation += 2;
          document.querySelector(
            'img'
          ).style.transform = `rotateY(${currentRotation}deg)`;
        }, 50);
      } else {
        rotateBtn.innerHTML = '<i class="fas fa-rotate text-xs"></i>';
        clearInterval(rotationInterval);
      }
    });
    
    // Expand functionality
    expandBtn.addEventListener('click', function () {
      isExpanded = !isExpanded;
      const img = document.querySelector('img');
    
      if (isExpanded) {
        img.classList.add('scale-150');
        expandBtn.innerHTML = '<i class="fas fa-compress text-xs"></i>';
      } else {
        img.classList.remove('scale-150');
        expandBtn.innerHTML = '<i class="fas fa-expand text-xs"></i>';
      }
    });
    
    // AR Try-On simulation
    arBtn.addEventListener('click', function () {
      showAIResponse(
        'Launching AR try-on experience. Please allow camera access to see how these sneakers look on you.',
        'Allow Camera',
        'Cancel'
      );
    });
    
    // View All button
    viewAllBtn.addEventListener('click', function () {
      showAIResponse(
        "Here are 8 similar products that match your preferences. I've highlighted the best options based on your purchase history.",
        'View Recommendations',
        'Close'
      );
    });
    
    // Save button
    saveBtn.addEventListener('click', function () {
      isSaved = !isSaved;
    
      if (isSaved) {
        saveBtn.innerHTML = '<i class="fas fa-heart mr-2 text-red-500"></i> Saved';
        saveBtn.classList.remove('bg-gray-100', 'dark:bg-gray-700');
        saveBtn.classList.add(
          'bg-red-50',
          'dark:bg-red-900/30',
          'text-red-500',
          'dark:text-red-300'
        );
        showAIResponse(
          'Added QuantumX Sneakers to your saved items. Would you like to set a price alert?',
          'Set Alert',
          'Not Now'
        );
      } else {
        saveBtn.innerHTML = '<i class="far fa-heart mr-2"></i> Save';
        saveBtn.classList.add('bg-gray-100', 'dark:bg-gray-700');
        saveBtn.classList.remove(
          'bg-red-50',
          'dark:bg-red-900/30',
          'text-red-500',
          'dark:text-red-300'
        );
      }
    });
    
    // Buy button
    buyBtn.addEventListener('click', function () {
      showAIResponse(
        'Excellent choice! The QuantumX sneakers will be shipped to your default address. Would you like to add 2-year protection for $29.99?',
        'Add Protection',
        'No Thanks'
      );
    });
    
    // AI Assistant interaction
    aiAssistant.addEventListener('click', function () {
      showAIResponse(
        "I'm your shopping assistant! I can compare products, check compatibility, or answer any questions. What would you like to know about these sneakers?",
        'Compare Products',
        'Ask a Question'
      );
    });
    
    // Simulate theme-based personalization
    function updatePersonalization() {
      const currentTheme = document.body.classList.contains('dark')
        ? 'dark'
        : 'light';
    
      // Update AI badge
      const aiBadge = document.querySelector('.product-badge');
    
      aiBadge.innerHTML =
        '<span class="ai-pulse">🤖</span><span class="ml-1">AI-PERSONALIZED</span>';
      aiBadge.style.background = 'var(--badge-gradient)';
    
      // Update all interactive elements
      document.querySelectorAll('.bg-chip').forEach((el) => {
        el.style.backgroundColor = 'var(--chip-bg)';
      });
    
      document.querySelectorAll('.text-primary').forEach((el) => {
        el.style.color = 'var(--text-primary)';
      });
    
      document.querySelectorAll('.text-secondary').forEach((el) => {
        el.style.color = 'var(--text-secondary)';
      });
    
      document.querySelectorAll('.bg-accent').forEach((el) => {
        el.style.backgroundColor = 'var(--accent-color)';
      });
    
      document.querySelectorAll('.border-primary').forEach((el) => {
        el.style.borderColor = 'var(--border-color)';
      });
    
      document.querySelectorAll('.bg-highlight').forEach((el) => {
        el.style.backgroundColor = 'var(--highlight-color)';
      });
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function () {
      loadTheme();
    
      // Close modal when clicking outside
      aiResponseModal.addEventListener('click', function (e) {
        if (e.target === aiResponseModal) {
          closeModal();
        }
      });
    
      // Close modal with Escape key
      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && !aiResponseModal.classList.contains('hidden')) {
          closeModal();
        }
      });
    });

    Final Output:

    modern-ecommerce-product-card-using-html-tailwind-and-javascript.gif

    Conclusion:

    You have successfully created a modern ecommerce product card using HTML, TailwindCSS, and JavaScript. This design can be reused for multiple products and styled further with animations, hover effects, or cart integration.

    By following these steps, you now know how to design a responsive product card that improves both user experience (UX) and website design.

    That’s a wrap!

    I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

    Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

    And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

    Thanks!
    Faraz 😊

    End of the article

    Subscribe to my Newsletter

    Get the latest posts delivered right to your inbox


    Latest Components

    Please allow ads on our site🥺