html - css 背景图像适应维度

标签 html css background-image

我正在尝试弄清楚如何仅在背景图像大于包含它的 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/

相关文章:

javascript - 如何将背景图像定位到 html 元素的左上角和右下角?

javascript - 具有不同结果的多个 div 的 CSS 控制

html - 使用 css 动态突出显示选项卡

javascript - 如何使左侧 div 可以使用空格键或向下箭头滚动而无需先单击?

html - Rails - Bootstrap 页脚消失了吗?

jquery - 如何将元素放入 Bootstrap 4 数据内容中?

html - 背景图像不显示在任何 IE 版本上

css - 从背景图像的中心显示文本

javascript - 库存 list Dynagrid 演示

javascript - Fabricjs - setBackgroundImage 为空 URL 导致 _setWidthHeight 中出现空引用错误