html - 缩放元素(和背景),但不缩放内容

标签 html css hover css-transitions css-transforms

我试图将鼠标悬停在一个元素上,使其变大几个百分点,但我想让标题和其中的内容保持在原来的位置。如果我只是将 scale(1.05) 添加到元素,内容也会缩放。如果我尝试使用 scale(0.95) 来反向缩放内部元素,则大小将与原始元素类似,但位置不会相同:

.container {
  display: block;
  width: 100%;
  padding: 50px;
}
.element {
  height: 562px;
  width: 590px;
  display: inline-block;
  position: relative;
  -webkit-transition: all 300ms ease-in-out;
  transition: all 300ms ease-in-out;
  background-image: url(https://images.unsplash.com/photo-1451906278231-17b8ff0a8880?crop=entropy&fit=crop&fm=jpg&h=975&ixjsv=2.1.0&ixlib=rb-0.3.5&q=80&w=1925);
  background-size: cover;
  background-position: center center;
}
.title {
  font-size: 45px;
  line-height: 48px;
  bottom: 10%;
  position: absolute;
  margin: 0 25px;
  color: #fff;
  text-shadow: 0 2px 0 rgba(0, 0, 0, 0.14);
  font-weight: 700;
  font-family: sans-serif;
  -webkit-transition: all 300ms ease-in-out;
  transition: all 300ms ease-in-out;
}
.element:hover {
  transform: scale(1.05);
  z-index: 10;
}
.element:hover .title {
  transform: scale(0.95);
}
<div class="container">
  <div class="element">
    <div class="title">This is the big title.</div>
  </div>
</div>

里面的内容是绝对放置的,所以我可能必须通过指定 bottomleft 属性来修复它,但我认为仍然会有一些过渡在内部元素上。

有什么办法可以解决这个问题吗?只是为了扩展元素而不影响内容?

最佳答案

将背景移动到单独的图层。

.container {
  position: relative;
  display: block;
  width: 300px;
  height: 300px;
  padding: 50px;
  margin: 50px auto;
}
.background {
  position: absolute;
  left: 0;
  top: 0;
  
  height: 100%;
  width: 100%;
  
  transition: all 300ms ease-in-out;
  background: url(https://images.unsplash.com/photo-1451906278231-17b8ff0a8880?crop=entropy&fit=crop&fm=jpg&h=975&ixjsv=2.1.0&ixlib=rb-0.3.5&q=80&w=1925) center center;
  background-size: cover;
}
.title {
  position: absolute;
  bottom: 10%;
  left: 0;

  margin: 0 25px;
  
  font-size: 45px;
  line-height: 48px;  
  color: #fff;
  font-weight: 700;
  font-family: sans-serif;
}
.container:hover .background {
  transform: scale(1.05);
}
<div class="container">
  <div class="background"></div>
  <div class="title">This is the big title.</div>
</div>

关于html - 缩放元素(和背景),但不缩放内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403867/

相关文章:

Python:使用 html 解析器提取特定数据

html - 当导航在屏幕调整大小时发生变化时将 div 移动到另一个下

html - 是否有可用于 CSS 重置的 HTML 测试文件?

Javascript - JQuery - OnHover NOT OnClick - 修改插件

html - 扩展悬停时的背景颜色

javascript - Angular 2 悬停事件

html - Cheerio 将单引号更改为双引号

javascript - ng-repeat - 如何避免复制 div 的输入内容

html - 位置 : absolute and automatic width trough content

javascript - 我可以从 JavaScript 访问无效/自定义 CSS 属性的值吗?