基础图片布局
常规图片插入
<img src="image.jpg" alt="描述文字" />
图片与文字混排
属性 | 说明 | 示例效果 |
---|---|---|
float:left |
文字环绕图片左侧 | 图片在左,文字右侧环绕 |
float:right |
文字环绕图片右侧 | 图片在右,文字左侧环绕 |
text-align |
控制图片水平对齐方式 | center 居中,left 左对齐 |
/ 清除浮动 / .clearfix::after { content: ""; display: block; clear: both; }
响应式图片适配
自适应宽度
img { max-width: 100%; height: auto; }
图片比例裁剪
.cropped-img { width: 300px; height: 200px; object-fit: cover; / 保持比例裁剪 / }
属性 | 说明 |
---|---|
object-fit |
控制图片填充方式 |
contain :保持比例缩放 |
|
cover :裁剪填充容器 |
|
fill :强制拉伸填满 |
高级交互效果
悬停动画
.hover-scale img { transition: transform 0.3s; } .hover-scale:hover img { transform: scale(1.05); }
懒加载优化
<img src="placeholder.jpg" data-src="real.jpg" class="lazy" /> <script> document.addEventListener('DOMContentLoaded', () => { const lazyImages = document.querySelectorAll('.lazy'); const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; img.classList.remove('lazy'); } }); }); lazyImages.forEach(img => observer.observe(img)); }); </script>
特殊布局技巧
背景图应用
.bg-image { background-image: url("bg.jpg"); background-size: cover; / 覆盖容器 / background-position: center; }
视差滚动效果
.parallax { background-attachment: fixed; / 固定背景 / height: 500px; }
常见问题与解决方案
问题类型 | 解决方案 |
---|---|
图片模糊 | 检查width/height 比例,使用object-fit 保留清晰度 |
加载速度过慢 | 启用懒加载,压缩图片体积(WebP格式),设置loading="lazy" 属性 |
移动端显示异常 | 使用max-width:100% ,添加viewport 元标签,测试不同设备 |
空白间隙问题 | 清除浮动(clearfix ),或使用display:flex 布局替代 |
相关问题与解答
Q1:如何让图片在不同屏幕尺寸下自动调整大小?
A1:使用响应式CSS,设置max-width:100%
和height:auto
,或通过<picture>
元素结合media
查询:
<picture>
<source media="(max-width:600px)" srcset="small.jpg">
<source media="(max-width:1200px)" srcset="medium.jpg">
<img src="large.jpg" alt="响应式图片">
</picture>
Q2:图片加载失败时如何显示默认占位图?
A2:使用onerror
事件监听,或设置<img>
的srcset
备用方案:
<img src="main.jpg" alt="主图" onerror="this.src='fallback.png'">
<!-或 –>
<img src="main.jpg" alt="主图" srcset="fallback.png 1x, main.jpg