You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

背景图片hover缩放效果问题:右侧缩小功能失效

问题排查:背景图片hover时右侧无缩小效果

我编写了HTML与CSS代码,想要实现背景图片hover时缩小的效果,目前该效果仅在顶部、底部和左侧生效,右侧边缘无变化,代码如下:

HTML代码

<html>
  <head>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <div class="header">
      <div class="obrazek"></div>
    </div>
  </body>
</html>

CSS代码

.header {
  width: 800px;
  height: 500px;
  background-color: rgb(218, 124, 124);
  overflow: hidden;
  position: relative;
  display: flex;
}

.obrazek {
  display: flex;
  padding: 25px;
  width: 100%;
  background-image: url(https://images.unsplash.com/photo-1667857399206-dc6d15189adc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80);
  background-size: cover;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  transition: top 0.3s ease-out, right 0.3s ease-out, bottom 0.3s ease-out,
    left 0.3s ease-out;
}

.obrazek:hover {
  top: 25px;
  right: 25px;
  bottom: 25px;
  left: 25px;
}

问题原因

.obrazek类同时设置了position: absolute(四边设为0,已自动填满父容器)和width: 100%,加上默认的box-sizing: content-box,导致元素实际宽度超出父容器。hover时设置right:25px的缩进效果被溢出部分遮挡,无法显示。

修复方案

有两种简单可行的修复方式:

方式1:移除多余的width: 100%

绝对定位且四边设为0的元素会自动填满父容器,无需额外设置宽度:

.obrazek {
  display: flex;
  padding: 25px;
  /* 移除width: 100% */
  background-image: url(https://images.unsplash.com/photo-1667857399206-dc6d15189adc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80);
  background-size: cover;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  transition: top 0.3s ease-out, right 0.3s ease-out, bottom 0.3s ease-out,
    left 0.3s ease-out;
}

方式2:添加box-sizing: border-box

若需保留width:100%,可通过该属性让内边距包含在宽度计算内,避免元素溢出:

.obrazek {
  display: flex;
  padding: 25px;
  width: 100%;
  box-sizing: border-box; /* 添加此行 */
  background-image: url(https://images.unsplash.com/photo-1667857399206-dc6d15189adc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80);
  background-size: cover;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  transition: top 0.3s ease-out, right 0.3s ease-out, bottom 0.3s ease-out,
    left 0.3s ease-out;
}

两种方式均可让hover时右侧的缩进效果正常显示,推荐方式1,更符合绝对定位元素的特性。


内容的提问来源于stack exchange,提问作者Magdalena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:55:30