背景附件:IMG的固定等价物

时间:2017-10-23 19:15:13

标签: html css background-image background-attachment

我试图找到仅与CSS相同的背景附件效果:已修复,适用于内联IMG元素。我已尝试过position:fixed,但从文档流中删除图像在这种情况下无效。

这是我的代码:

https://codepen.io/julianapong/pen/vewmzw



body{
  height:2000px;
  padding:0;
  margin:0;
}

*{
  box-sizing:border-box;
}

.bg_fixed{
  float:left;
  display:inline-block;
  width:32vw;
  height: 100vh;
  background-attachment:fixed;
  background-size:contain;
  background-repeat:no-repeat;
}

.img_absolute{
  width:32vw;
  height:100vh;
  float:left;
  position:relative;
}

.img_absolute img{
  height:100%;
  width:100%;
  object-fit:cover;
  position:absolute;
  left:0;
  z-index:-1;
}

.img_fixed{
  position:fixed;
  width:33vw;
  height: 100vh;
  z-index:-1
  right:0;
}

.img_fixed_container{
  border:1px solid red;
   width:32vw;
  height: 100vh;
  right:0;
  overflow:hidden;
}

<div class="bg_fixed" style=
     "background-image:url('https://i.imgur.com/KEMR0bJ.jpg')">
       bg_fixed
</div>

<div class="img_absolute"><img src="https://i.imgur.com/KEMR0bJ.jpg" /><span >img_absolute</span></div>

<div class="img_fixed_container"><img class="img_fixed" src="https://i.imgur.com/KEMR0bJ.jpg" /><span >img_fixed</span></div>
&#13;
&#13;
&#13;

理想情况下,我喜欢使用与bg_fixed相同的行为滚动img_absolute或img_fixed。是否有任何CSS技巧可以做到这一点?

1 个答案:

答案 0 :(得分:2)

.img_fixed {
  position: fixed;
  width: 33vw;
  height: 100vh;
  z-index: -1;
  right: 0;
  transform: perspective(0px);
  /* added */
}

.img_fixed_container {
  border: 1px solid red;
  width: 33vw;
  height: 100vh;
  right: 0;
  overflow: hidden;
  /* added */
  position: absolute;
  clip: rect(0, auto, auto, 0);
}

代码段示范:

&#13;
&#13;
body {
  height: 2000px;
  padding: 0;
  margin: 0;
}

* {
  box-sizing: border-box;
}

.bg_fixed {
  float: left;
  display: inline-block;
  width: 33vw;
  height: 100vh;
  background-attachment: fixed;
  background-size: contain;
  background-repeat: no-repeat;
}

.img_absolute {
  width: 33vw;
  height: 100vh;
  float: left;
  position: relative;
}

.img_absolute img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  position: absolute;
  left: 0;
  z-index: -1;
}

.img_fixed {
  position: fixed;
  width: 33vw;
  height: 100vh;
  z-index: -1;
  right: 0;
  transform: perspective(0px);
  /* added */
}

.img_fixed_container {
  border: 1px solid red;
  width: 33vw;
  height: 100vh;
  right: 0;
  overflow: hidden;
  /* added */
  position: absolute;
  clip: rect(0, auto, auto, 0);
}
&#13;
<div class="bg_fixed" style="background-image:url('https://placehold.it/500x700')">
  bg_fixed
</div>

<div class="img_absolute"><img src="https://placehold.it/500x700" /><span>img_absolute</span></div>

<div class="img_fixed_container"><img class="img_fixed" src="https://placehold.it/500x700" /><span>img_fixed</span></div>
&#13;
&#13;
&#13;