Frontend Development 9 min read

CSS Grid Layout for E‑commerce Product Cards

The article shows how using CSS Grid instead of nested Flex containers can halve the HTML and CSS needed for e‑commerce product cards by defining rows and columns, simplifying markup to a few elements while preserving layout for images, titles, prices, badges, and actions.

DaTaobao Tech
DaTaobao Tech
DaTaobao Tech
CSS Grid Layout for E‑commerce Product Cards

This article introduces the use of CSS Grid layout for designing product cards, compares it with the traditional Flex‑based approach, and provides a concise learning path with practical examples.

Problem with Flex layout : To arrange a product card that contains an image, title, price, badge, sales, action button and other elements, developers often split the layout into many nested containers, resulting in verbose HTML and CSS.

Typical Flex HTML (simplified):

<div className="card">
  <div className="card-top">
    <div className="card-top-left">商品图</div>
    <div className="card-top-right">
      <div className="card-top-right-top">热销指数</div>
      <div className="card-top-right-bottom">商品信息</div>
    </div>
  </div>
  <div className="card-bottom">
    <div className="card-bottom-left">商品价格</div>
    <div className="card-bottom-right">行动按钮</div>
  </div>
</div>

Corresponding Flex CSS (simplified):

.card {
  display: flex;
  flex-direction: column;
}
.card-top {
  flex: 1;
  display: flex;
}
.card-bottom {
  height: 50rpx;
  display: flex;
  justify-content: space-between;
}

Grid solution : By setting the container to display: grid and defining rows and columns, the same card can be expressed with far fewer elements.

Grid HTML (simplified):

<div className="card">
  <div className="img">商品图</div>
  <div className="guide">热销指数</div>
  <div className="info">商品信息</div>
  <div className="price">商品价格</div>
  <div className="action">行动按钮</div>
</div>

Grid CSS (core part):

.card {
  display: grid;
  grid-template-columns: 262rpx 1fr;
  grid-template-rows: 50rpx 212rpx 1fr;
}
.img { grid-row: 1 / 3; }
.guide { grid-column-start: 2; }
.info { grid-row-start: 2; grid-column-start: 2; }
.price { grid-column-start: 1; grid-row-start: 3; }
.action { grid-column-start: 2; grid-row-start: 3; }

Only the image element needs an explicit grid area; the rest flow naturally, reducing HTML from 13 lines to 7 and CSS from 33 lines to 13 – a code reduction of over 50%.

The article also lists useful resources for mastering CSS Grid, such as MDN’s Grid guide, CSS‑Grid‑Garden, Ruanyifeng’s tutorial, and interactive generators.

Front-endlayoutCSSCSS GridhtmlResponsive Design
DaTaobao Tech
Written by

DaTaobao Tech

Official account of DaTaobao Technology

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.