我的布局包含背景图片和两列内容。 列是视口高度的100%和视口宽度的50%(将屏幕分成两个垂直的一半)。背景图像也是视口高。
当我将右列进一步向右移动时,背景图像的那一部分随之移动,在两半之间留下间隙。
到目前为止一切都有效,但我希望将背景图像置于页面中心...
代码:
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>
&#13;
答案 0 :(得分:1)
实际上,只使用一张图片就可以达到理想的效果,但只有在图像为正方形时才有效。
只需使用background-position
属性的四值语法;从background-position
列的右侧设置-50vh
为.main-left
,从-50vh
列的左侧设置.main-right
。
html,
body,
main {
height: 100%;
overflow: hidden;
}
.main-left,
.main-right {
height: 100vh;
width: 50vw;
position: absolute;
top: 0;
background: url('https://unsplash.it/750/750');
background-size: auto 100%;
background-repeat: no-repeat;
box-sizing: border-box;
}
.main-left {
left: 0;
background-position: right -50vh top 0;
}
.main-right {
left: 51vw;
background-position: left -50vh top 0;
}
&#13;
<body>
<div class="main-left">
...left content here ...
</div>
<div class="main-right">
...right content here ...
</div>
</body>
&#13;
这里是JSFiddle。
有关background-position
财产的更多信息。
答案 1 :(得分:1)
代码:
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>