如何实现电商网页商品卡片每行展示3个且不改变原有样式?
解决步骤
- 调整HTML结构:给所有商品卡片套一层外层容器,用来控制flex排列规则
- 修正错误样式:删除全局不合理的border设置,去掉商品卡片的固定高度限制,改用flex布局实现底部价格栏的排列,避免负margin导致的布局错乱
- 配置flex排列规则:给外层容器设置自动换行、间距,实现每行3个卡片的效果
修改后的完整代码
HTML代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Card set</title> <link rel="stylesheet" type="text/css" href="cardset.css"> <script src="script.js"></script> </head> <body> <!-- 新增外层flex容器 --> <div class="product-container"> <div class="product-item"> <img src="boots.png" alt="女靴"> <div class="product-list"> <h3>Ботинки женские</h3> <h4>Модные ботинки из натурального нубука. Согреют Ваши ноги во время зимних морозов.</h4> <!-- 底部价格栏套一层容器方便flex布局 --> <div class="price-wrap"> <span class="price">1999</span> <span class="sell">руб.</span> <div class="cart"> <img src="cart.png" alt="购物车"> </div> </div> </div> </div> <div class="product-item"> <img src="boots.png" alt="女靴"> <div class="product-list"> <h3>Ботинки женские</h3> <h4>Модные ботинки из натурального нубука. Согреют Ваши ноги во время зимних морозов.</h4> <div class="price-wrap"> <span class="price">1999</span> <span class="sell">руб.</span> <div class="cart"> <img src="cart.png" alt="购物车"> </div> </div> </div> </div> <!-- 可继续添加更多商品卡片,自动适配每行3个的规则 --> </div> </body> </html>
CSS代码
* { box-sizing: border-box; margin: 0; padding: 0; } /* 新增外层容器样式 */ .product-container { display: flex; flex-wrap: wrap; /* 卡片之间的横向和纵向间距,可按需调整 */ gap: 20px; padding: 20px; width: 100%; } .product-item { /* 每行3个,减去间距后计算宽度,也可直接写固定值300px */ width: calc((100% - 40px) / 3); text-align: center; border: 1px solid #e2e2e2; background: white; font-family: "Roboto"; } .product-item img { display: inline-block; width: 100%; border-bottom: 1px solid #e2e2e2; } .product-list { background: #fafafa; padding: 15px; } .product-list h3 { font-size: 20px; font-family: "Roboto"; text-align: left; margin: 0 0 10px 0; font-weight: 400; color: #333333; } .product-list h4 { font-size: 15px; font-family: "Roboto"; text-align: left; margin: 0 0 15px 0; font-weight: 400; color: #666666; } /* 新增价格栏flex布局 */ .price-wrap { display: flex; align-items: center; gap: 5px; } .sell { font-size: 20px; font-family: "Roboto"; color: #333333; margin-right: auto; } .price { font-size: 35px; font-family: "Roboto"; color: #333333; } .cart img { width: 30px; }
如果需要固定卡片宽度为300px,只需要把.product-item的width属性改成300px,给.product-container添加justify-content: flex-start属性即可,外层容器宽度足够的情况下会自动每行排列3个卡片。
内容的提问来源于stack exchange,提问作者Darentina
相关产品推荐
相关产品推荐

