html - 拆分和居中视口(viewport)高背景图像

标签 html css

我有一个带有背景图像和两列内容的布局。 列是视口(viewport)高度的 100% 和视口(viewport)宽度的 50%(将屏幕垂直分成两半)。背景图像也是视口(viewport)高。

当我将右列进一步向右移动时,背景图像的那部分会随之移动,在两半之间留下间隙。

到目前为止一切正常,但我希望背景图像位于页面的中心...

代码:

html,
body,
main {
  height: 100%;
  overflow: hidden;
}
.main-left,
.main-right {
  height: 100vh;
  width: 50vw;
  position: absolute;
  top: 0;
  background: url('https://unsplash.it/150/150');
  background-size: auto 100%;
  background-repeat: no-repeat;
  box-sizing: border-box;
}
.main-left {
  left: 0;
  background-position: left 0;
}
.main-right {
  left: 50vw;
  background-position: -50vw 0;
}
<body>
  <div class="main-left">
    ...left content here ...
  </div>
  <div class="main-right">
    ...right content here ...
  </div>
</body>

JSFiddle

现在是这样的: enter image description here

它应该是这样的: enter image description here

这就是我想要用它做的: enter image description here

最佳答案

  • 给两列一个 :before 伪元素,其尺寸与视口(viewport)相同
  • 将这些伪元素的背景图像设置为您在单个元素中的尺寸(在我的例子中:100vh auto;中心顶部 - 但覆盖或包含也可以)。
  • 将右列移动视口(viewport)的一半,并将 right:before 元素向后移动相同的量。
  • 隐藏列的溢出

代码:

	
html,
body,
main {
  height: 100%;
  overflow:hidden;
}

.main-left, 
.main-right {
  height: 100vh;
  width: 50vw;
  position: absolute;
  overflow: hidden;
 }

.main-left {
  left: 0;
}

.main-right {
  left: 52vw;
}

.main-left:before {
  content: "";
  z-index:-3;
  position: absolute;
  width: 100vw;
  height: 100vh;
  background: url('https://unsplash.it/500/400');
  background-size: cover;
}

.main-right:before {
  content: "";
  z-index:-3;
  position: absolute;
  left: -50vw;
  width: 100vw;
  height: 100vh;
  background: url('https://unsplash.it/500/400');
  background-size: cover;
}
<body>
  <div class="main-left">
    ...left content here ...
  </div>
  <div class="main-right">
    ...right content here ...
  </div>
</body>

关于html - 拆分和居中视口(viewport)高背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39749688/

相关文章:

html - 使用非表情符号版本的 unicode 字符(highcharts 和纯 html)

html - 如何使这个导航菜单居中

java - 在服务器(servlet)端检测下拉列表的值时出现问题

javascript - jquery 计算高度和宽度并在其背后设置动画内容

javascript - 将向上和向下箭头切换为图像

css - 文本嵌套在 View 中,如何使 View 作为内容的大小?

html - 删除最后一个 li 边框

html - 从 Logo 填充 - HTML

jquery - Twitter bootstrap - 为选项卡式导航添加动画/过渡效果

css - 按照元素在文档中出现的顺序获取元素