Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can use HTML and CSS to create a shopping-cart layout, but they cannot add products, change quantities, remove items, or calculate a live total on their own. Those actions need JavaScript or server-side code. This guide builds an accessible browser demo and explains what must change before using a cart for real orders.

What HTML and CSS can—and cannot—do

HTML defines the cart’s structure and controls; CSS styles and arranges them. A static HTML/CSS mock-up can show products, quantity fields, and a checkout button, but it cannot update cart state or calculate totals when a shopper interacts with it. JavaScript can manage that state in the browser. For a real store, server-side code must verify the order and handle checkout.

Approach Cart state and persistence Price, stock, discounts, and shipping validation Payments, accounts, and orders Effort
Static HTML and CSS mock-up No interactive state; changes do not persist. Not validated. No payment processing or order persistence. Lowest; useful for practicing layout.
Browser-only JavaScript demo Can update cart state and save a demo cart in localStorage on that browser. Values in the browser are not authoritative. Does not provide trusted payment processing or durable order management. Suitable for learning interactions; requires more code than a mock-up.
Commerce platform or custom backend Can persist orders and, depending on the implementation, support accounts and multiple devices. Trusted server-side validation is required. Can integrate a payment provider and order management. More setup and maintenance; integrations depend on the platform or backend.

Build the cart’s semantic HTML

Use native form controls so the cart works with keyboards and assistive technology. MDN recommends a real <button> instead of a <div> programmed to act like one; native buttons can be reached with Tab and activated with Space, Return, or Enter. W3C WAI recommends associating each control with a <label>, grouping related controls with <fieldset> and <legend> when appropriate, and giving concise instructions. See the MDN forms guide, MDN button accessibility guidance, and W3C WAI forms tutorial.

For a small example, put product cards and a cart summary in the page, then let JavaScript render cart lines into the cart region. A visible label should identify each quantity input, and buttons should say what they do. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
<main>
  <h1>Shop</h1>
  <section aria-labelledby="products-heading">
    <h2 id="products-heading">Products</h2>
    <article class="product">
      <h3>Blue T-shirt</h3>
      <p>$24.00</p>
      <button type="button" data-add="tee-blue">Add Blue T-shirt to cart</button>
    </article>
  </section>

  <section aria-labelledby="cart-heading">
    <h2 id="cart-heading">Your cart</h2>
    <ul id="cart-lines"></ul>
    <p>Subtotal: <span id="subtotal">$0.00</span></p>
    <p id="cart-status" role="status" aria-live="polite"></p>
    <button type="button" id="checkout">Continue to checkout</button>
  </section>
</main>

The list gives JavaScript a place to render line items. When it renders a quantity field, include a label such as “Quantity for Blue T-shirt,” plus buttons with specific names such as “Remove Blue T-shirt.” The checkout button in this demo is only a control: without a real checkout flow behind it, it must not imply that an order or payment has been placed.

Model cart state and calculate the subtotal

Keep one record per product variant, with a stable product or variant ID, a display name, a price, and a quantity. A Shopify theme-development reference describes a line item as a product variant and its associated quantity; see Shopify’s cart documentation. Treat the cart collection as the source for what the demo displays: after adding, changing, or removing a line, render the lines and calculate the subtotal again.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const products = {
  "tee-blue": { id: "tee-blue", name: "Blue T-shirt", price: 24.00 }
};

let cart = [];

function addToCart(productId) {
  const existing = cart.find(item => item.id === productId);
  if (existing) {
    existing.quantity += 1;
  } else {
    const product = products[productId];
    if (!product) return;
    cart.push({ ...product, quantity: 1 });
  }
  renderCart();
}

function renderCart() {
  const lines = document.querySelector("#cart-lines");
  lines.replaceChildren();

  for (const item of cart) {
    const li = document.createElement("li");
    li.textContent = `${item.name} — $${(item.price * item.quantity).toFixed(2)} `;

    const label = document.createElement("label");
    label.textContent = `Quantity for ${item.name}`;
    const input = document.createElement("input");
    input.type = "number";
    input.min = "1";
    input.value = String(item.quantity);
    input.addEventListener("change", () => {
      const quantity = Number.parseInt(input.value, 10);
      if (!Number.isInteger(quantity) || quantity < 1) {
        input.value = String(item.quantity);
        return;
      }
      item.quantity = quantity;
      renderCart();
    });
    label.append(input);
    li.append(label);

    const remove = document.createElement("button");
    remove.type = "button";
    remove.textContent = `Remove ${item.name}`;
    remove.addEventListener("click", () => {
      cart = cart.filter(cartItem => cartItem.id !== item.id);
      renderCart();
    });
    li.append(remove);
    lines.append(li);
  }

  const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  document.querySelector("#subtotal").textContent = `$${subtotal.toFixed(2)}`;
}

document.addEventListener("click", event => {
  const button = event.target.closest("[data-add]");
  if (button) addToCart(button.dataset.add);
});

This example keeps state in memory, so refreshing the page clears it. It also uses prices from a JavaScript object only to demonstrate a subtotal. A browser user can inspect or alter client-side data, so these values cannot establish what a real shopper owes.

Style the layout for narrow screens

Use grid or flexbox for product cards and the cart summary, and let the layout stack on small screens. Keep text readable, give controls comfortable hit areas, and preserve a visible keyboard-focus indicator. Responsive layout helps keep controls usable without changing their native behavior.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
.shop-layout {
  display: grid;
  grid-template-columns: minmax(0, 2fr) minmax(16rem, 1fr);
  gap: 2rem;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
  gap: 1rem;
}

button, input {
  min-height: 2.75rem;
}

:focus-visible {
  outline: 3px solid #1456cc;
  outline-offset: 2px;
}

@media (max-width: 48rem) {
  .shop-layout {
    grid-template-columns: 1fr;
  }
}

Do not communicate sale status, errors, or stock messages by color alone. Give product images meaningful alternative text when they convey product information; use empty alt="" text for purely decorative images. Announce important cart updates in a status region, as in the example, without moving focus unexpectedly. For custom visuals or controls, preserve the underlying native element; W3C WAI explains this progressive-enhancement approach in its custom-controls guidance. MDN’s broader accessibility guide covers semantic HTML, labels, alternative text, and responsive considerations.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Persist a learning cart without trusting it

For a browser-only demo, JavaScript can save the cart to localStorage and restore it after a refresh in the same browser. A 2026 vanilla shopping-cart tutorial demonstrates product data, quantity controls, a live subtotal, an item-count badge, and localStorage persistence, while distinguishing that demo from checkout backed by a payment provider. Restored data still comes from the browser, so it is useful for learning or convenience—not as an authority for inventory, price, or payment.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

To add persistence, save cart state after changes and load it at startup, validating the data before rendering. For example:

const CART_KEY = "demo-cart";

function saveCart() {
  localStorage.setItem(CART_KEY, JSON.stringify(cart));
}

function loadCart() {
  try {
    const saved = JSON.parse(localStorage.getItem(CART_KEY) || "[]");
    if (!Array.isArray(saved)) return;
    cart = saved.filter(item =>
      item &&
      typeof item.id === "string" &&
      Number.isInteger(item.quantity) &&
      item.quantity > 0 &&
      products[item.id]
    ).map(item => ({
      ...products[item.id],
      quantity: item.quantity
    }));
  } catch {
    cart = [];
  }
  renderCart();
}

loadCart();

Call saveCart() whenever cart state changes, before or after rendering. The load routine above deliberately takes product details from the local product catalog rather than accepting saved names or prices. That makes the demo more consistent, but the catalog itself remains client-side and is not a trusted source for a transaction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What a production checkout must do

A browser cart is not an order system. Before accepting payment, the server must look up current products and variants, validate quantities and availability, apply eligible discounts, calculate shipping and tax as appropriate, and calculate the payable total from trusted data. Do not accept a browser-submitted price, stock level, discount, shipping charge, or total as authoritative.

The server should then create a payment session through the chosen payment provider and preserve the order through a trusted backend flow. Authentication, secure payment handling, order persistence, and integrations require a commerce platform or a backend designed for them; HTML and CSS alone cannot supply those capabilities. The exact implementation depends on the platform and payment provider, so do not treat the demo’s checkout button as a production checkout.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.