带背景图片的中心主页div



我想创建一个主页,该页面的中心背景图像在整个图像周围都有30px填充。足够简单,但无法实现。

   <body>
    <div class="megawrapper">
      <div class="home-page">
       </div>
    </div>
   </body>
.megawrapper {
    position: absolute;
    overflow-x: hidden;
    overflow-y: hidden;
    width: 100%;
    height: 100%;
}
.home-page {    
    padding: 30px;
    background-image: url(images/street.jpg);
    background-position: 50% 50%;
    background-size: cover;
    background-repeat: no-repeat;
}

https://jsfiddle.net/geike/okyg5p2o/

使用边框:

body {
  margin: 0;
  padding: 0;
}
.wrapper {
  background: #333 url("http://www.descoperalocuri.ro/wp-content/uploads/2013/11/Riga-o-imagine-clasic%C4%83-pentru-centrul-vechi-1024x575.jpg") no-repeat 50% 50% /cover;
  min-height: calc(100vh - 60px);
  border: 30px solid #333;
}
<div class="wrapper"></div>

使用填充:

body {
  margin: 0;
  padding: 30px;
  background-color: #333;
}
.wrapper {
  background: url("http://www.descoperalocuri.ro/wp-content/uploads/2013/11/Riga-o-imagine-clasic%C4%83-pentru-centrul-vechi-1024x575.jpg") no-repeat 50% 50% /cover;
  min-height: calc(100vh - 60px);
}
<div class="wrapper"></div>

使用Margin:

body {
  margin: 0;
  padding: 0;
  background-color: #333;
}
.wrapper {
  margin: 30px;
  background: url("http://www.descoperalocuri.ro/wp-content/uploads/2013/11/Riga-o-imagine-clasic%C4%83-pentru-centrul-vechi-1024x575.jpg") no-repeat 50% 50% /cover;
  min-height: calc(100vh - 60px);
}
<div class="wrapper"></div>

我提出的解决方案(没有包装器):

body {
  padding: 30px;
  margin: 0;
  background: url("http://www.descoperalocuri.ro/wp-content/uploads/2013/11/Riga-o-imagine-clasic%C4%83-pentru-centrul-vechi-1024x575.jpg") no-repeat 50% 50% /cover;
  background-clip: content-box;
  box-sizing: border-box;
  /* min-height: calc(100vh - 60px); */
  min-height: 200vh; /* this is here to see page scrolling. remove and uncomment previous line */
}
body::before {
  position: fixed;
  z-index: 1;
  display: block;
  content: '';
  top: 0;
  left: 0;
  pointer-events: none;
  width: 100vw;
  height: 100vh;
  border: 30px solid #333;
  box-sizing: border-box;
}

我使身体的高度是最后一个视口的两倍,以显示当内容延伸到折叠上方时会发生什么。

您只需要为megawrapper设置背景属性:

body {
  margin: 0;
  padding: 0;
}
.megawrapper {
    position: absolute;
    overflow-x: hidden;
    overflow-y: hidden;
    width: 100%;
    height: 100%;
    background-image: url('http://lorempixel.com/output/nightlife-q-c-640-480-9.jpg');
    background-repeat: no-repeat;
    background-position: 30px 30px;
    background-size: calc(100% - 60px);
}
.home-page {
    padding: 60px;
    background-color: gray;
}
    <div class="megawrapper">
      <div class="home-page"> 
      </div>
    </div>

最新更新