2014-11-14 146 views
1

我想弄清楚如何调整背景图像的大小,只有当它比只包含CSS的div大时。css背景图像适应尺寸

<div id="container> 
</div> 

#container{ 
width: 100px; 
height: 100px; 
background-image: url("...myimagepath"); 
} 

如果图像大于100x100像素,应当调整,但如果是小的,我需要保持它的中心和不适应。在我的代码中,它的作用与小于div的图像一致,而图像没有为较大的图像调整大小。

+0

发现这是一个有趣的问题cos重复背景有时可能会看起来有点naff,因为背景可能会掉出容器。 – 2014-11-14 15:46:24

回答

-1

您可以通过将图像放在位于背景中的div中来将其冻结。

所以HTML:

<div id="container> 
    <div id="background"> 
    <img src="...myimagepath"> 
    </div> 
    Container content here. 
</div> 

CSS:

#container{ 
    width: 100px;  /* Your original dimensions */ 
    height: 100px; 
    position: relative; /* Lets anything in it be positioned relative to it */ 
} 

#background{ 
    width: 100%;   /* Same width as parent container */ 
    height: 100%;  /* Ditto height */ 
    position: absolute; /* Take out of document flow. Default position 0,0 */ 
    z-index: -1;   /* Push it behind anything else in its container */ 
} 

#background img { 
    max-width: 100%;  /* Don't let it get wider than its container */ 
    max-height: 100%; /* Nor taller */ 
    display: block;  /* Lets margins be set (otherwise in-line) */ 
    position: absolute: /* Lets us position it */ 
    top: 0;    /* Put it at the top ... */ 
    left: 0;    /* on the far left ... */ 
    bottom: 0;   /* and at the bottom (makes sense later) */ 
    right: 0;   /* and the far right (ditto) */ 
    margin: auto;  /* Best compromise between left/right & top/bottom = centre */ 
} 

我似乎记得上半年有可能是奇浏览器不会将零的上,左,等正常。如果是这样,请改用1px等值。

+0

我的规格需要使用背景图片而不是,有没有办法避免? – user1638466 2014-11-14 15:44:31

+0

对不起,我不知道一个。也许问这样的原因呢?如果是这样的图像不打印,你可以在css中处理。也许你可以给他们正确的东西,让他们快乐,但不是他们认为应该完成的。 – 2014-11-14 15:49:27

+0

这是一个性能的原因,它不是网络,但嵌入式系统;) – user1638466 2014-11-14 15:54:17