这是一个 example .
我想裁剪背景图像,然后将裁剪图像用作更大(尺寸)元素的背景。我的意思是 div 比它的背景大,我不需要重复。现在,当 background-repeat
取消注释时,元素消失。但我认为它会显示裁剪的未重复背景。
#div {
background-image: url(http://dummyimage.com/600x400/000/fff);
padding: 10px;
width: 100px;
height: 100px;
background-position: 0px -100px;
background-size: 100px 100px;
background-repeat: no-repeat; /*comment this*/
position: absolute;
}
<div id="div"></div>
最佳答案
由于分配给背景的位置,添加 background-repeat: no-repeat
设置时,background
消失。它相对于原点设置在 0px -100px
处。您尚未为 background-origin
设置任何值所以默认值(即 padding-box
将被使用)和图像的高度仅为 100px。因此,当您指示浏览器不要重复图像时,可见区域中没有任何内容。
对于演示中所示的情况,图像不需要裁剪,因为它的大小只有 100 x 100(使用 background-size
设置)并且div
框的大小(以及所有边上 10px 的 padding
)大于图像(请参阅下面的代码片段以查看实际情况)。
如果你的意思是说你想使用 background-size
属性将 600 x 400 图像缩放为 100 x 100 并将其显示在 div
中,那么您可以按照下面的代码片段本身所示进行操作。
.div {
/*position: absolute; commented out for demo */
background-image: url(http://dummyimage.com/600x400/000/fff);
padding: 10px;
width: 100px;
height: 100px;
/*background-position: 0px -100px; - this makes it positioned above the viewable area of the box container, so remove it */
background-size: 100px 100px;
background-repeat: no-repeat;
border: 1px solid red; /* just to show how box is bigger than image */
}
/* If the image has to be centered within the div */
.div.centered { background-position: 50% 50%; }
/* Just for demo */
div{ margin: 10px;}
<div class="div"></div>
<div class="div centered"></div>
另一方面,如果您打算使用 background-position
来指定应该进行裁剪的区域,那么这样做是不可能的。对于这种情况,您应该避免使用 background-size
,而是像下面的代码片段一样使用 background-position
。
此处,通过将 background-position
指定为 -240px -140px
,图像中位于坐标 (240,140) 至 (360,260) 内的部分图像将显示在框中。由于框的大小(包括填充),它显示 120 x 120 像素的图像。
.div {
position: absolute;
background-image: url(http://dummyimage.com/600x400/000/fff);
padding: 10px;
width: 100px;
height: 100px;
background-position: -240px -140px;
background-repeat: no-repeat;
border: 1px solid red; /* just to show how box is bigger than image */
}
/* Just for demo */
div{ margin: 10px; }
<div class="div"></div>
关于css - background-size 和 background-repeat 究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33864288/