如何设置两个空 div(用于背景图像)的样式,正好一个位于另一个之上



我试图将两个空<div>一个直接排在另一个上方,基本上第一<div>占据屏幕的上半部分,第二<div>占据屏幕的下半部分。两个<div>都包含背景图像,并且需要完美对齐(即顶部<div>的底部需要与底部<div>的顶部齐平(,以便我尝试创建的效果有意义。

到目前为止,我所拥有的是:

html {
  height: 100%;
}
body {
  display: block;
  text-align: center;
  height: 100%;
  min-height: 100%;
  position: relative;
  padding: 0;
  margin: 0;
}
.top {
  display: block;
  background-image: url(photo-top.jpg);
  background-position: 50%;
  background-size: cover;
  height:100%;
  min-height: 100%;
  width:100%;
  top: 0;
  margin: 0;
  padding: 0;
}
.bottom {
  display: block;
  background-image: url(photo-bottom.jpg);
  background-position: 50%;
  background-size: cover;
  height:100%;
  min-height: 100%;
  width:100%;
  bottom: 0;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <div class="top"></div>
    <div class="bottom"></div>
  </body>
</html>

这会在顶部和底部图像之间放置一个巨大的空白区域。我该如何解决这个问题?

您可以使用

以下解决方案,将每个<div>50vh作为高度:

html {
  height: 100%;
}
body {
  display: block;
  text-align: center;
  height: 100%;
  min-height: 100%;
  position: relative;
  padding: 0;
  margin: 0;
}
.top {
  display: block;
  background-color:red;
  background-image: url(https://picsum.photos/id/1025/200/300);
  background-position: 50%;
  background-size: auto 100%;
  background-repeat:no-repeat;
  height: 50vh;
  width: 100%;
  margin: 0;
  padding: 0;
}
.bottom {
  display: block;
  background-color:blue;
  background-image: url(https://picsum.photos/id/1025/200/300);
  background-position: 50%;
  background-size: auto 100%;
  background-repeat:no-repeat;
  height:50vh;
  width:100%;
  margin: 0;
  padding: 0;
}
<div class="top"></div>
<div class="bottom"></div>


如果两个<div>元素下面没有其他内容,您可以使用绝对定位元素:

html {
  height: 100%;
}
body {
  display: block;
  text-align: center;
  height: 100%;
  min-height: 100%;
  position: absolute;
  padding: 0;
  margin: 0;
  top:0;
  bottom:0;
  left:0;
  right:0;
}
.top {
  display: block;
  background-color:red;
  background-image: url(https://picsum.photos/id/1025/200/300);
  background-position: 50%;
  background-size: auto 100%;
  background-repeat:no-repeat;
  height: 50vh;
  width: 100%;
  margin: 0;
  padding: 0;
  position:absolute;
  top:0;
  bottom:50%;
  left:0;
  right:0;
}
.bottom {
  display: block;
  background-color:blue;
  background-image: url(https://picsum.photos/id/1025/200/300);
  background-position: 50%;
  background-size: auto 100%;
  background-repeat:no-repeat;
  height:50vh;
  width:100%;
  margin: 0;
  padding: 0;
  position:absolute;
  top:50%;
  bottom:0;
  left:0;
  right:0;
}
<div class="top"></div>
<div class="bottom"></div>

最新更新