首页 > 解决方案 > 如何设置两个空 div(用于背景图像)的样式,它们恰好一个在另一个之上?

问题描述

我正在尝试将两个空<div>的 s 直接排在另一个上方,基本上第一个<div>占据屏幕的上半部分,第二个<div>占据屏幕的下半部分。两个<div>s 都包含背景图像,并且需要完美对齐(即顶部的底部<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>

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

标签: htmlcss

解决方案


You can use the following solution using 50vh for each <div> as height:

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>


In case there is no other content below the two <div> elements you can use absolute positioned elements:

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>


推荐阅读