这是html:
<section class="bg">
<h3>this is heading</h3>
<div>other content</div>
</section>
我的背景图片有以下内容:
.bg {
background: url("img/watercolor-bkgrd.png") center top / 100% 75% no-repeat
}
现在我想将背景图像从顶部稍微降低(例如:100px),这样h3标题就不会停留在背景图像的顶部。如何在不修改html结构的情况下实现它?请注意,我必须保留上面css中已有的内容,例如水平居中图像等等。
答案 0 :(得分:2)
使用background position偏移值。
这确实要求你知道上面元素的高度。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
h3 {
height: 60px;
background: lightblue;
opacity: .5;
}
.bg {
height: 100vh;
background-image: url(http://www.placebacon.net/400/200?image=0);
background-repeat: no-repeat;
background-position: center top 60px;
}
&#13;
<section class="bg">
<h3>this is heading</h3>
<div>other content</div>
</section>
&#13;
答案 1 :(得分:2)
只需将“top”更改为“100px”或您要移动的任何值。
请参阅此工作片段(我使用的是80px):
.bg {
height:400px; /* for testing */
background: url("http://oi67.tinypic.com/28a11js.jpg") center 80px / 100% 75% no-repeat
}
<section class="bg">
<h3>this is heading</h3>
<div>other content</div>
</section>
这是以与您自己的代码相同的方式设置内联background-position
属性。
问题是确保图片始终位于<h3>
元素下:您可以将<h3>
元素设置为固定高度,并为背景位置使用相同的值。
h3元素的未知高度
如果您不知道<h3>
元素的高度,那么如何将图片作为背景添加到<div>
下面的<h3>
,如下所示:
.bg div{
height:400px; /* for testing */
background: url("http://oi67.tinypic.com/28a11js.jpg") center top / 100% 75% no-repeat
}
<section class="bg">
<h3>this is heading</h3>
<div>other content</div>
</section>
答案 2 :(得分:1)
你正在寻找css属性&#34;背景位置&#34; (Mozilla Docs)
这允许您在div中设置背景图像的初始顶部和左侧位置。
背景位置:左上角; 只需将以下内容添加到.bg类:
background-position: 0 100px;