HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>电商产品展示</title>
</head>
<body>
<div class="product-container">
<div class="product">
<img src="product1.jpg" alt="商品图片">
<h3>商品标题</h3>
<p>商品价格</p>
<p>商品描述</p>
</div>
<div class="product">
<img src="product2.jpg" alt="商品图片">
<h3>商品标题</h3>
<p>商品价格</p>
<p>商品描述</p>
</div>
<div class="product">
<img src="product3.jpg" alt="商品图片">
<h3>商品标题</h3>
<p>商品价格</p>
<p>商品描述</p>
</div>
<div class="product">
<img src="product4.jpg" alt="商品图片">
<h3>商品标题</h3>
<p>商品价格</p>
<p>商品描述</p>
</div>
</div>
</body>
</html>
CSS 代码
/* 通用样式 */
.product-container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.product {
text-align: center;
width: 100%;
padding: 20px;
}
.product img {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto 10px;
}
/* 桌面端样式 */
@media (min-width: 768px) {
.product-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 20px;
}
}
解释如何确保图片和文字在不同分辨率下的合理缩放与对齐
- 图片缩放:
- 设置
img
标签的 max - width: 100%; height: auto;
。这样图片在任何分辨率下,宽度都不会超过其父元素(.product
容器)的宽度,并且高度会按比例自动缩放,保持图片的原始纵横比,避免图片变形。
display: block; margin: 0 auto 10px;
使图片在 .product
容器中水平居中,并在图片下方添加 10px 的间距。
- 文字对齐:
- 在
.product
容器上设置 text - align: center;
,这使得标题(<h3>
)、价格(<p>
)和描述(<p>
)等文本内容在水平方向上居中对齐。
- 使用 Flexbox 和 Grid 布局来控制整体的排版结构。在移动端,Flexbox 的
flex - wrap: wrap
和 justify - content: space - around
确保商品在单列排列时均匀分布在容器内。在桌面端,Grid 的 grid - template - columns: repeat(4, 1fr);
创建四列布局,grid - gap: 20px;
设置列与列之间的间距,使得商品展示更加整齐有序。