一、文本环绕图片
1.1 使用float
属性
img.float-left {
float: left;
margin-right: 10px;
}
p {
margin-left: 50px;
}
<p>这里有一些文字...</p>
<img src="image.jpg" alt="示例图片" class="float-left">
1.2 使用display: inline-block;
img.inline-block {
display: inline-block;
margin-right: 10px;
}
<p>这里有一些文字...</p>
<img src="image.jpg" alt="示例图片" class="inline-block">
二、图片居中
2.1 使用margin: auto;
.container {
width: 100%;
text-align: center;
}
.container img {
margin: auto;
}
<div class="container">
<img src="image.jpg" alt="示例图片">
</div>
2.2 使用Flexbox
.container-flex {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
.container-flex img {
width: 100%;
height: auto;
}
<div class="container-flex">
<img src="image.jpg" alt="示例图片">
</div>
三、图片响应式设计
3.1 使用百分比宽度
img.responsive {
width: 100%;
height: auto;
}
3.2 使用媒体查询
使用媒体查询可以针对不同屏幕尺寸应用不同的CSS样式。
@media (max-width: 600px) {
img.responsive {
width: 50%;
}
}
四、图片懒加载
<img class="lazy-load" data-src="image.jpg" alt="示例图片">
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy-load"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy-load");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for browsers that don't support IntersectionObserver
}
});