应用场景:响应式网页设计 - 产品展示页面
背景描述
你正在为一个电子产品在线商店设计一个产品展示页面。这个页面需要展示产品的图片、名称、价格以及描述。为了确保页面在不同设备和屏幕尺寸上都能提供良好的用户体验,你决定使用媒体查询来根据设备的宽度应用不同的CSS样式。这样,当用户在手机、平板或桌面电脑上访问页面时,布局会自动调整以适应屏幕大小。
具体实现
HTML 结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Product Showcase</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="product-container">
<div class="product-image">
<img src="product.jpg" alt="Product Image">
</div>
<div class="product-details">
<h1 class="product-name">Super Gadget X3000</h1>
<p class="product-price">$999.99</p>
<p class="product-description">
The Super Gadget X3000 is the latest innovation in tech, combining cutting-edge features with sleek design.
</p>
<button class="buy-now">Buy Now</button>
</div>
</div>
</body>
</html>
CSS 样式(使用媒体查询)
/* 基本样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 1rem;
}
.product-container {
display: flex;
flex-direction: column;
align-items: center;
background: #fff;
padding: 2rem;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 1200px;
margin: 0 auto;
}
.product-image img {
width: 100%;
height: auto;
max-width: 500px;
}
.product-details {
text-align: center;
margin-top: 1rem;
}
.product-name {
font-size: 2rem;
margin-bottom: 0.5rem;
}
.product-price {
font-size: 1.5rem;
color: #f60;
margin-bottom: 1rem;
}
.product-description {
font-size: 1rem;
margin-bottom: 1.5rem;
}
.buy-now {
padding: 1rem 2rem;
font-size: 1rem;
color: #fff;
background-color: #007bff;
border: none;
cursor: pointer;
border-radius: 5px;
}
/* 媒体查询:平板设备(宽度 >= 768px) */
@media (min-width: 768px) {
.product-container {
flex-direction: row;
justify-content: space-between;
}
.product-image img {
max-width: 45%;
}
.product-details {
text-align: left;
max-width: 50%;
}
}
/* 媒体查询:桌面设备(宽度 >= 1024px) */
@media (min-width: 1024px) {
.product-container {
padding: 3rem;
}
.product-name {
font-size: 2.5rem;
}
.product-price {
font-size: 2rem;
}
.product-description {
font-size: 1.2rem;
}
.buy-now {
padding: 1.2rem 2.5rem;
font-size: 1.2rem;
}
}
解释与美化
-
HTML 部分:
- 使用<div class="product-container">作为产品展示的主容器。
- 产品图片放在<div class="product-image">内,并使用<img>标签加载图片。
产品名称、价格和描述放在<div class="product-details">内,并使用相应的HTML标签进行结构化。 - 添加一个购买按钮<button class="buy-now">。
-
CSS 部分:
-
基本样式:
- 重置所有元素的默认外边距和内边距,设置box-sizing为border-box。
- 设置页面的字体家族、背景颜色和内边距。
- 为产品容器设置灵活的布局(默认垂直排列),居中对齐,设置背景颜色、内边距和阴影效果。
- 设置产品图片的宽度为100%(自适应容器),并限制最大宽度为500px(防止过大)。
- 设置产品详情部分的文本对齐方式、外边距和字体大小。
- 设置购买按钮的样式,包括内边距、字体大小、颜色、背景颜色、边框、光标样式和圆角。
-
媒体查询:
- 平板设备(宽度 >= 768px):
- 将产品容器布局改为水平排列,并设置两端对齐。
- 调整产品图片的最大宽度为45%。
- 调整产品详情部分的文本对齐方式为左对齐,并限制最大宽度为50%。
- 桌面设备(宽度 >= 1024px):
- 增加产品容器的内边距。
- 增大产品名称、价格和描述的字体大小。
- 增大购买按钮的内边距和字体大小,使其更加醒目和易于点击。
-
通过这种方式,你可以创建一个响应式的产品展示页面,当用户在不同设备上访问时,页面布局和样式会自动调整以提供最佳的用户体验。使用媒体查询,你可以根据设备的特性(如宽度)应用不同的CSS样式,使页面更加灵活和美观。

大屏幕.png

小屏幕.png