0

这是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>

+0

你把它定位一百个像素到div的左侧,所以当你打开,因为它是关闭的股利的主要部分重复播放功能,它不会呈现在所有 –

回答

4

background消失时background-repeat: no-repeat设置,因为分配给背景的位置加入。关于原点设置在0px -100px。您尚未为background-origin设置任何值,因此默认值(即,将使用padding-box)以及图像的高度仅为100px。因此,当您指示浏览器不重复图像时,可见区域中没有任何内容。

对于演示说明的情况下,图像并不需要进行剪裁,因为它的尺寸只有100×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>