如何让div自适应内容高度,hover放大图片时不出现垂直滚动条
解决方案
问题核心是图片容器缩放后的可视区域超出了父级overflow限制,无需隐藏溢出,只要给承载容器预留足够的溢出空间即可解决,具体修改如下:
核心修改点
- 给包裹三个图片容器的flex父节点添加内边距,预留1.05倍缩放产生的溢出空间,16px即可适配当前缩放比例
- 补充img元素的自适应样式,确保图片填满父容器,避免缩放错位
- 清理CSS中重复的transform声明
- 可按需调整transform-origin属性控制缩放锚点,设置为
center bottom可让缩放更多向顶部延伸,减少底部溢出
修改后代码
CSS部分
h1 { letter-spacing: -.015em; font-size: 3.5rem; font-weight: 400; line-height: 1.1; } .subtitle{ font-size: 1.25em; } @media (min-width: 1024px) { h1 { letter-spacing: -.015em; font-size: 4.5rem; font-weight: 400; line-height: 1.1; } .subtitle{ font-size: 1.65em; } } @media (min-width: 768px) { .img-container { width:345px !important; height:580px !important; } } .img-container { width:173px; height:290px; transition: all 0.2s linear; } /* 新增图片自适应样式 */ .img-container img { width: 100%; height: 100%; object-fit: cover; } .img-container:hover { transform: scale(1.05); /* 按需调整缩放锚点,不需要可删除 transform-origin: center bottom; */ } /* 新增图片列表容器内边距 */ .image-list-wrapper { padding: 16px; }
HTML部分
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/> <section id="home" class="lg:pl-28 flex flex-wrap flex-row w-full"> <div class="flex flex-col w-full lg:w-6/12 xl:w-5/12 justify-center pl-12 lg:pl-0 pr-28 pt-36 lg:pt-32 xl:pt-52"> <p class="text-md lg:text-lg text-left text-gray-500">Post Title</p> <h1 class="mb-4 pt-5 pb-9 text-left">Title 1</h1> <p class="subtitle leading-normal text-gray-500 mb-8 text-left">Subtitle</p> </div> <!--Right Col--> <div class="w-full lg:w-6/12 xl:w-7/12 overflow-x:hidden flex items-center lg:pt-32 xl:pt-52"> <!-- 新增自定义class --> <div class="flex gap-4 image-list-wrapper"> <div class="flex-initial img-container"> <img src="https://via.placeholder.com/345x580" alt="示例图片"> </div> <div class="flex-initial img-container"> <img src="https://via.placeholder.com/345x580" alt="示例图片"> </div> <div class="flex-initial img-container"> <img src="https://via.placeholder.com/345x580" alt="示例图片"> </div> </div> </div> </section>
可选优化
如果修改后仍出现横向滚动条,可将右列的overflow-x:hidden属性移到最外层的section标签上,同时删除右列的该属性,既可以保证页面不会出现全局横向滚动条,图片放大的部分也不会被父容器裁切。
内容的提问来源于stack exchange,提问作者jac
相关产品推荐
相关产品推荐

