求助:实现含figure-figcaption的响应式网站(需明日完成)
响应式Figure+Figcaption网站解决方案(新手友好,快速实现)
别担心!我给你准备了一套完整的可直接使用的代码,完美适配桌面、平板和手机,而且代码注释很清楚,你只要替换自己的图片和文字就行,绝对能在明天搞定~
完整代码(HTML+CSS)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- 关键:添加viewport元标签,确保移动端正确缩放 --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>响应式图片展示站</title> <style> /* 全局重置,消除默认边距和padding */ * { margin: 0; padding: 0; box-sizing: border-box; } #container { max-width: 1200px; /* 桌面端最大宽度,避免太宽 */ margin: 2rem auto; /* 上下间距,左右居中 */ padding: 0 1rem; /* 移动端左右留边,防止贴边 */ } h1 { text-align: center; margin-bottom: 2rem; color: #333; } /* 核心:网格布局 */ #grid { display: grid; /* 桌面端:4列,列间距1rem */ grid-template-columns: repeat(4, 1fr); gap: 1rem; } /* 统一所有figure的样式 */ #grid figure { background-color: #f8f8f8; border-radius: 8px; overflow: hidden; /* 让图片圆角生效 */ box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 轻微阴影,提升质感 */ } /* 图片自适应容器 */ #grid img { width: 100%; height: auto; /* 保持图片比例 */ display: block; /* 消除图片下方的空白间隙 */ } /* 标题样式 */ #grid figcaption { padding: 0.8rem; text-align: center; color: #555; font-size: 0.9rem; } /* 平板端适配(屏幕宽度≤768px) */ @media (max-width: 768px) { #grid { grid-template-columns: repeat(2, 1fr); /* 改成2列 */ } } /* 手机端适配(屏幕宽度≤480px) */ @media (max-width: 480px) { #grid { grid-template-columns: 1fr; /* 改成1列 */ } } </style> </head> <body> <div id="container"> <h1>My Image Gallery</h1> <div id="grid"> <figure id="r"> <img src="http://placehold.it/300x200" alt="描述图片内容的文字"> <figcaption>图片标题1</figcaption> </figure> <figure id="p"> <img src="http://placehold.it/300x200" alt="描述图片内容的文字"> <figcaption>图片标题2</figcaption> </figure> <figure id="c"> <img src="http://placehold.it/300x200" alt="描述图片内容的文字"> <figcaption>图片标题3</figcaption> </figure> <figure id="s"> <img src="http://placehold.it/300x200" alt="描述图片内容的文字"> <figcaption>图片标题4</figcaption> </figure> </div> </div> </body> </html>
关键部分说明(帮你理解代码)
- Viewport元标签:这是移动端适配的核心,必须加!它告诉浏览器按照设备屏幕宽度来渲染页面,不会出现缩放混乱的问题。
- CSS Grid布局:用
grid-template-columns控制列数,repeat(4,1fr)表示4列等宽,gap是列/行之间的间距,让布局更美观。 - 图片自适应:
width:100%让图片填满容器,height:auto保证图片比例不变,不会拉伸变形。 - 媒体查询:通过
@media设置不同屏幕宽度下的布局,平板改成2列,手机改成1列,完美适配各种设备。 - 细节优化:加了轻微阴影、圆角、背景色,让整体视觉效果更专业,同时消除了默认的边距和空白间隙。
使用方法
- 把上面的代码复制到一个新的
.html文件里(比如index.html) - 替换
img标签里的src为你自己的图片链接,修改alt和figcaption的文字内容 - 直接用浏览器打开这个文件,就能看到效果啦!
这个方案完全满足你的需求,而且代码简单易懂,没有复杂的框架,新手也能快速上手,绝对能在明天完成任务~
内容的提问来源于stack exchange,提问作者user3566608
相关产品推荐
相关产品推荐

