使用picture标签加载png/webp双图时图片无法正常缩放求助
解决3D书本效果中picture标签导致的图片显示问题
问题原因
你猜的没错,问题确实出在.book > :first-child这段CSS上。原来的结构里,.book的第一个子元素是<img>,这段样式直接作用在图片上,让它定位并应用3D变换。但换成<picture>标签后,.book > :first-child选中的是<picture>元素,而内部的<img>没有继承对应的尺寸和定位样式,导致图片以原始大小显示,完全脱离了3D书本的布局。
解决方案
只需要调整CSS,让<picture>和内部的<img>都适配3D书本的容器尺寸,同时保持3D变换效果:
修改后的CSS代码
.book-container { display: flex; align-items: center; justify-content: center; perspective: 600px; } @keyframes initAnimation { 0% { transform: rotateY(0deg); } 100% { transform: rotateY(-30deg); } } .book { width: 200px; height: 320px; position: relative; transform-style: preserve-3d; transform: rotateY(-30deg); transition: 1s ease; animation: 1s ease 0s 1 initAnimation; } .book:hover { transform: rotateY(0deg); } .book > :first-child { position: absolute; top: 0; left: 0; width: 200px; height: 320px; transform: translateZ(25px); border-radius: 0 2px 2px 0; box-shadow: 5px 5px 20px #E5E4E2; } /* 新增:让picture和内部img适配容器 */ .book picture { display: block; width: 100%; height: 100%; } .book img { width: 100%; height: 100%; object-fit: cover; /* 保持图片比例并填满容器 */ border-radius: inherit; /* 继承父元素的圆角样式 */ } .book::before { position: absolute; content: ' '; left: 0; top: 3px; width: 48px; height: 314px; transform: translateX(172px) rotateY(90deg); background: linear-gradient(90deg, #fff 0%, #f9f9f9 5%, #fff 10%, #f9f9f9 15%, #fff 20%, #f9f9f9 25%, #fff 30%, #f9f9f9 35%, #fff 40%, #f9f9f9 45%, #fff 50%, #f9f9f9 55%, #fff 60%, #f9f9f9 65%, #fff 70%, #f9f9f9 75%, #fff 80%, #f9f9f9 85%, #fff 90%, #f9f9f9 95%, #fff 100% ); } .book::after { position: absolute; top: 0; left: 0; content: ' '; width: 200px; height: 320px; transform: translateZ(-25px); background-color: #01060f; border-radius: 0 2px 2px 0; box-shadow: -10px 0 50px 10px #666; }
对应的HTML结构(无需改动)
<a class="book-container" href="#" target="_blank" rel="noreferrer noopener"> <div class="book"> <picture> <source srcset="https://i.ibb.co/grB6NbQ/THE-BOOK-cover-image.webp" type="image/webp"> <source srcset="https://i.sstatic.net/1MPyO.png" type="image/png"> <img alt="My Cover" src="https://i.sstatic.net/1MPyO.png"/> </picture> </div> </a>
方案说明
.book > :first-child现在作用在<picture>上,给它设置定位和3D变换,确保它作为书本封面层存在.book picture设置为块级元素并填满容器,承接父元素的尺寸和变换属性.book img设置宽高100%并使用object-fit: cover,保证图片适配容器大小同时保持比例,不会变形
不需要用JS切换图片源,<picture>标签是实现多格式兼容的标准方案,调整CSS就能完美适配你的3D书本效果。
内容的提问来源于stack exchange,提问作者Federico Navarrete
相关产品推荐
相关产品推荐

