定位背景图像-x从上到下

Position background image - x from top and x from bottom

本文关键字:从上到下 图像 背景 定位      更新时间:2023-09-26

http://jsfiddle.net/sXLg7/1/

我正在尝试放置背景图像,以便在div的顶部和底部留下50像素的空间。

通过这个属性,我可以轻松地将背景图像定位在顶部下方50像素

background-position: 0 50px;

但是,我如何定位这个背景图像,使底部有50像素的空间

我试过这个

 background-position: 0 50px 0 50px;

但这似乎不起作用。我假设它将接受4个参数,用于从4个方向进行定位。

有什么想法吗?

请尝试后台剪辑属性:

padding-top:50px;
padding-bottom:50px;
background-clip: content-box;

查看此Fiddle:http://jsfiddle.net/A5u8j/

不幸的是,我认为这是不可能的。根据它的用途,您可能可以使用两个div,其中内部div具有背景图像和顶部&底部边距为50px;

尝试添加这两个属性

background-size: 500px 400px;
background-position: 0 50px;

您不能在后台位置执行此操作;然而,您可以使用一个伪元素将某些东西破解在一起。

http://jsfiddle.net/sXLg7/3/

以下是更新后的CSS:

.test {
    border: 2px solid red;
    height: 500px;
    width: 500px;
    position: relative;
}
.test:before {
    content: '';
    z-index: -1;
    background-image: url("http://www.reallyslick.com/pictures/helios.jpg");
    background-repeat: no-repeat;
    position: absolute;
    top: 50px; left: 0; right: 0; bottom: 50px;
}

您可以使用CSS background-size,尽管浏览器支持有些有限。

.test {
    border: 2px solid red;
    background-image: url("http://www.reallyslick.com/pictures/helios.jpg");
    background-position: 0 50px;
    background-size:100% 400px;
    height: 500px;
    width: 500px;
    background-repeat: no-repeat;
}

工作示例


备用方法

或者,可以使用两个嵌套元素。外层的顶部和底部都有衬垫,这样内层就不会到达顶部/底部。

我使用了CSS box-sizing,所以填充在高度中被考虑在内。请注意,对此的支持也有些有限。

工作示例


或者,可以从外部元素的高度减去填充。

工作示例

这里有一种方法。放置一个具有绝对位置和负z索引的图像。将它放在测试分区中的任何内容后面。

http://jsfiddle.net/sXLg7/8/

html

<div class="test">
    Text on top of background.
    <img src="http://www.reallyslick.com/pictures/helios.jpg" class="background"/>
</div>

和css

.test {    
border: 2px solid red;
height: 500px;
width: 500px;
overflow: hidden;
position: relative;
color: #fff;
}
.test .background {
    position: absolute;
    bottom: 50px;
    left: 0;
    z-index: -1;
}

您可以在元素上放置一个50像素的边框。

http://jsfiddle.net/sXLg7/10/

html

<div class="test"></div>

css

.test {
  outline: 2px solid red;
  border: 50px solid transparent;
  background-image: url("http://www.reallyslick.com/pictures/helios.jpg");
  background-position: center;
  background-size: auto 100%;
  height: 500px;
  width: 500px;
  background-repeat: no-repeat;
  box-sizing: border-box;
}

为什么不加一个50像素的边距?像这样:

.test {
    border: 2px solid red;
    background-image: url("http://www.reallyslick.com/pictures/helios.jpg");
    height: 500px;
    width: 500px;
    background-repeat: no-repeat;
    margin:50px;
}

http://jsfiddle.net/4Dmkv/