CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。大图片居中是指将一张较大的图片在网页中水平和垂直居中显示。
img {
display: block;
margin-left: auto;
margin-right: auto;
}应用场景:适用于简单的图片居中需求,特别是当图片宽度大于容器宽度时。
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 使容器高度占满整个视口 */
}
img {
max-width: 100%;
max-height: 100%;
}应用场景:适用于需要在容器中垂直居中显示图片的场景,特别是当容器高度不固定时。
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 使容器高度占满整个视口 */
}
img {
max-width: 100%;
max-height: 100%;
}应用场景:适用于需要在整个视口中完全居中显示图片的场景。
原因:大图片文件较大,加载时间较长。
解决方法:
<picture>元素或srcset属性提供不同分辨率的图片,以适应不同设备。<picture>
<source srcset="large.jpg" media="(min-width: 1200px)">
<source srcset="medium.jpg" media="(min-width: 768px)">
<img src="small.jpg" alt="Example">
</picture><img data-src="large.jpg" alt="Example" class="lazyload">document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazyload"));
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("lazyload");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
});通过以上方法,可以有效地解决大图片居中显示的各种问题,并提升网页的性能和用户体验。