css - 纯 CSS 视差的水平偏移从何而来?

标签 css parallax

我正在尝试按照 this post 中的方法生成纯 CSS 视差效果.它主要有效;但是,当视差元素不是全 Angular 时,会出现一些伪像。

在下面的代码片段中,hero 元素(具有指定的尺寸)旨在比页面的其余部分滚动得更慢。容器的 perspective-origin 恰好指向英雄元素的中间,因此应用 transform: translateZ(-1px) scale(2); 到英雄不应该移动它根本。但它确实会产生几个像素的水平偏移。 (垂直位置很好。)

为什么会发生这种情况,如何解决?

.container { 
  height: 500px; 
  background: #eee; 
  overflow-y: auto; 
  overflow-x: hidden; 
  perspective: 1px; 
  perspective-origin: 50% 171.5px; 
}

.hero { 
  background: url('http://via.placeholder.com/1256x343'); 
  height: 343px; 
  margin-left: auto; 
  margin-right: auto; 
  transform: translateZ(-1px) scale(2); 
  max-width: 1256px; 
}

.main { 
  background: rebeccapurple; 
  height: 2000px; 
  margin-left: auto; 
  margin-right: auto; 
  max-width: 1256px; 
}
<div class="container">
  <div class="hero"></div>
  <div class="main">Scroll me down</div>
</div>

最佳答案

此布局基于 hero 元素完美地位于容器的中心。

那么,perspective-origin-x: 50% 就可以了....

但是,只要右侧有滚动条,content-box 大小在 container 和 hero 中就不再相同,并且会错过对齐。

看看this post有关更多详细信息和可能适用于您的情况的解决方案

html,body{
  margin: 0;
  height: 100%;
  overflow: hidden;
  background: #000;
}
#wrapper1{
  width: calc(100% + 17px);
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
}
#wrapper2{
  width: 100%;
  height: 100%;
  perspective: 1px;
  perspective-origin: calc(100% - 17px) center;
  overflow-y: scroll;
}
#wrapper3{
  width: 100%;
  max-width: 100vw;
  transform-style: preserve-3d;
}
.parallax_layer1{
  transform-origin: 100% center;
  transform: translateZ(-.4px) scale(1.4); /* scale=1-translateZ/perspective */
  z-index: -1;
  position: relative;
}
section{
  background: #111;
  height: 50vh;
  box-shadow: 0 0 50px rgba(0,0,0,0.7);
  width: 100%;
}
img{
  width: 100%;
  height: 80vh;
  margin: -5vh 0;
  object-fit: cover;
}

关于css - 纯 CSS 视差的水平偏移从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686499/

相关文章:

jquery - 多重视差背景

c++ - 如何获取CCSprite添加到CCParallaxNode的位置?

css - 将 Bootstrap 品牌定位在导航栏旁边

html - 类上的自定义 CSS

c# - 如何为 <% %> 之间的文本添加颜色样式

jquery - 视差滚动网站(stellar.js)中对象的不一致定位

javascript - 视差 : how to keep absolute positioned images inside the relative div?

html - 固定侧边栏内的狮身人面像雪花石膏主题滚动

css - 不同类别下的同一属性或一个类别具有一个属性

html - 在部分中创建视差页面和定位元素