背景图像可以比div本身大吗?

mat*_*att 72 css background image

我有一个100%宽度的页脚div.它的高度约为50px,具体取决于其内容.

是否有可能为#footer提供一个溢出这个div的背景图像?

图像大约是800x600px,我希望它位于页脚的左下角.它应该有点像我的网站的背景图像,但我已经在我的身体上设置了背景图像.我需要另一个位于我网站左下角的图像,#footer div对此非常适合.

#footer {
    clear: both;
    width: 100%;
    margin: 0;
    padding: 30px 0 0;
    background:#eee url(images/bodybgbottomleft.png) no-repeat left bottom fixed;
}
Run Code Online (Sandbox Code Playgroud)

图像设置为页脚,但不会溢出div.是否有可能实现这一目标?

overflow:visible 不做这个工作!

小智 148

有一个非常简单的技巧.将该div的填充设置为正数,将边距设置为negativ

#wrapper {
     background: url(xxx.jpeg);
     padding-left: 10px;
     margin-left: -10px;
}
Run Code Online (Sandbox Code Playgroud)

  • 尽管它很有效,但这会修改​​包装器的大小,并且不会将其延伸到外面。这使得所有其他不依赖于填充重新定位的项目 (4认同)
  • 谢谢伙计,我认为这应该被接受。 (3认同)

Dan*_*ham 45

我不相信你可以让背景图像溢出它的div.放置在图像标签中的图像可以溢出其父div,但背景图像受到它们作为背景的div的限制.


小智 9

不,你不能.

但作为一个可靠的解决方法,我建议将第一个div分类为position:relative并用于div::before创建包含图像的底层元素.分类为position:absolute您可以相对于您的初始div移动它.

不要忘记向该新元素添加内容.这是一些例子:

div {
  position: relative;
}    

div::before {
  content: ""; /* empty but necessary */
  position: absolute;
  background: ...
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您希望它在父div的"顶部",请div::after改为使用.


Pan*_*pes 5

使用背景尺寸的封面对我有用。

#footer {
    background-color: #eee;
    background-image: url(images/bodybgbottomleft.png);
    background-repeat: no-repeat;
    background-size: cover;
    clear: both;
    width: 100%;
    margin: 0;
    padding: 30px 0 0;
}
Run Code Online (Sandbox Code Playgroud)

显然要注意支持问题,请检查“我可以使用”:http : //caniuse.com/#search=background-size


Pav*_*huk 5

使用 trasform:scale(1.1) 属性使背景图像变大,用position:relative向上移动;顶部:-10px;

<div class="home-hero">
  <div class="home-hero__img"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
.home-hero__img{
  position:relative;
  top:-10px;
  transform: scale(1.1);
  background: {
    size: contain;
    image: url('image.svg');
  }
}
Run Code Online (Sandbox Code Playgroud)