【问题标题】:CSS - How to get div on top of background image?CSS - 如何在背景图像之上获取 div?
【发布时间】:2018-10-05 03:16:09
【问题描述】:

我有一个页面一半的背景图片,我在它下面有一个 div,我还想把它的四分之一放在背景图片上方。我试图将 padding-top 放在 profile 类上,但在将 background-pic 和 profile 包装在 div 中时它不起作用。

CSS:

.background-pic{
      background-image: url('https://images.pexels.com/photos/825262/pexels-photo-825262.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
      height: 60%;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      background-color: rgba(0,0,0,0);
    }

.profile{
  padding-top: 300px;
}

HTML:

<div class="background-pic">
    </div>
    <div class="container">
      <div class="profile" style="background-color: grey; height : 300px;">
        <div class="profile-pic">
        </div>
      </div>
    </div>

【问题讨论】:

标签: html css


【解决方案1】:

您可以将否定的margin-bottom 应用于第一个元素。

.background-pic {
  background-image: url(https://www.placecage.com/600/400);
  height: 400px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  margin-bottom: -100px;
}

.content {
  padding-top: 300px;
  background: rgba(10, 150, 10, .4);
}
<div class="background-pic"></div>
<div class="content">Profile content</div>

【讨论】:

  • 不客气。每次我可以展示尼古拉斯凯奇的照片,都会让我很开心。
【解决方案2】:

您需要做的就是在.profile 元素上设置一个负边距。我清理了你的 HTML 和 CSS,所以你可以按照这个:

.background-pic{
   background-image: url('https://images.pexels.com/photos/825262/pexels-photo-825262.jpeg');
   background-position: center;
   background-repeat: no-repeat;
   background-size: cover;
   height: 500px;
   width: 100%;
}

.profile{
  background-color: pink;
  height: 500px; /* optional if you put enough content in */
  margin: -100px auto 0 auto;
  padding: 25px 50px;
  width: 600px;
}
<div class="background-pic"></div>
<div class="profile">
   Content goes here.
</div>

演示: https://codepen.io/staypuftman/pen/QrNZPz

【讨论】:

    【解决方案3】:

    .background-pic的CSS中添加属性position : absolute

    .profile 的CSS 中添加属性position : relative,然后根据需要更改.profile 中文本的填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 2015-09-09
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 2013-09-20
      相关资源
      最近更新 更多