我正在尝试弄清楚如何仅在背景图像大于包含它的 div 时仅使用 CSS 调整背景图像的大小。
<div id="container>
</div>
#container{
width: 100px;
height: 100px;
background-image: url("...myimagepath");
}
如果图像大于 100x100 像素,则应调整大小,但如果较小,我需要将其保持居中而不进行调整。在我的代码中,对于小于 div 的图像,它按方面工作,而不会为更大的图像调整大小。
最佳答案
您可以通过将图像放在背景中的 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 之类的值。
关于html - css 背景图像适应维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26931971/