CSS-仅放大背景(无覆盖文字)

时间:2018-09-10 21:24:14

标签: css background bootstrap-4 zoom

我正在尝试放大背景图像。下面的代码代表一个具有背景图像的可点击元素。我的问题是它会放大该div中的所有内容,包括子div。我只想放大背景图片(保留覆盖文字不变)

<a class="outer-tile tile-text" href="#">
    <div class="inner-tile d-flex flex-column align-items-start" style="background-image: url('https://picsum.photos/200/300')">
      <div class="mb-auto p-2">
        <span class="b-dark p-1">MyTag</span>
      </div>
      <div class="b-dark w-100 p-2">
        <h3>My Title</h3>
        <p>This is the content</p>
      </div>
    </div>
  </a>


.outer-tile {
    overflow: hidden;
    height: 400px;
}

.inner-tile {
    height: 100%;
    width: 100%;
    background-size: cover;
    background-position: center;
    transition: all 0.5s ease;
}

.inner-tile:hover {
    transform: scale(1.2);
}

这里是codepen

我如何仅使背景放大而不使文本放大?

1 个答案:

答案 0 :(得分:2)

您可以将背景图像放置在文本元素的同级元素(而不是父元素)上。然后使用定位和z-index将其放置在它们后面:

.outer-tile {
    overflow: hidden;
    height: 400px;
  position:relative;
}

.tile-underlay {
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    z-index:-1;
    background-size: cover;
    background-position: center;
    transition: all 0.5s ease;
}

.outer-tile:hover .tile-underlay {
    transform: scale(1.2);
}

  <a class="outer-tile tile-text" href="#">
      <div class="tile-underlay d-flex flex-column align-items-start" style="background-image: url('https://picsum.photos/200/300')"></div>
      <div class="mb-auto p-2">
        <span class="b-dark p-1">MyTag</span>
      </div>
      <div class="b-dark w-100 p-2">
        <h3>My Title</h3>
        <p>This is the content</p>
      </div>

  </a>

https://codepen.io/anon/pen/NLyYKY