鼠标悬停放大figure元素时如何避免边框同步放大?
解决方案
核心原因是transform: scale()会缩放元素的所有属性(包括边框),所以要把边框与需要缩放的内容分离,下面提供两种可行方案:
方案一:新增内部容器(推荐,结构清晰)
把图片和标题放到一个内部容器中,让figure仅负责承载边框,悬停时只缩放内部容器,边框保持原始尺寸。
修改后的HTML
<figure id="pub_img"> <div class="content-wrapper"> <img src="https://picsum.photos/600/300"> <figcaption>Lorem Ipsum</figcaption> </div> </figure>
修改后的CSS
#pub_img { border: 1px solid #555; float: right; width: 80px; position: relative; overflow: visible; /* 避免缩放内容被裁剪 */ } /* 内部容器承载可缩放内容 */ #pub_img .content-wrapper { width: 100%; transition: transform .4s ease-in-out; /* 仅针对transform过渡,性能更优 */ } #pub_img:hover .content-wrapper { transform: scale(4); transform-origin: top right; /* 从右上角开始缩放,匹配原浮动位置 */ } figure img { width: 100%; margin: 0; padding: 0; vertical-align: middle; } figure figcaption { border-top: 1px solid gray; background-color: #ffffff; font-size: 0.2em; text-align: justify; }
方案二:用伪元素模拟边框(无需修改HTML)
通过绝对定位的伪元素添加边框,伪元素不会被figure的transform影响,因为它基于父元素的原始尺寸定位。
修改后的CSS
#pub_img { float: right; width: 80px; position: relative; transition: transform .4s ease-in-out; } /* 用伪元素创建边框,不参与缩放 */ #pub_img::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border: 1px solid #555; pointer-events: none; /* 不干扰鼠标悬停事件 */ } #pub_img:hover { transform: scale(4); transform-origin: top right; } figure img { width: 100%; margin: 0; padding: 0; vertical-align: middle; } figure figcaption { border-top: 1px solid gray; background-color: #ffffff; font-size: 0.2em; text-align: justify; }
内容的提问来源于stack exchange,提问作者FooBar
相关产品推荐
相关产品推荐

