如何根据图像大小在 css 中添加背景大小?

How to add background-size in css based on image size?

我正在开发一个项目,用户可以在其中 select 或上传图片,图片将显示在这些圈子内。图像被动态添加为背景图像。当我尝试设置背景大小时,问题就出现了。如果图像比圆圈大,我希望它有一个背景大小的封面,所以它会缩小。如果图片小于圆圈,我不希望它放大或任何设置无背景大小达到此效果。

关于如何实现这一点有什么想法吗?

主要 html 看起来像这样:

<div class="image-boundary">
    <div class="content">
        <div class="image-boundary-photo img-responsive" style="background-image: url('https://www.fillmurray.com/g/100/100');" alt="">
        </div>
    /div>
</div>

css:

.module-list-home .content .image-boundary-photo {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
  background-repeat: no-repeat;
  background-position: center;
}

这是我的例子的codepen。 http://codepen.io/johnsonjpj/pen/zKyGZp?editors=1100 第三张图片应该有一个 background-size: cover;因为它更大,而其他的应该保持原样。

您可能会从 background-size 设置“contain”中受益匪浅。

我已将其内联添加到您的笔中,以供查看:http://codepen.io/cam5/pen/vXvNOq?editors=1100

当它们太小时它会变大,所以可能不完全是你想要的。但是查询图像的大小很可能会涉及一些javascript。这是一种仅 CSS 的方法。

<div class="image-boundary-photo img-responsive" 
     style="background-image: url('https://www.fillmurray.com/g/100/100');
     background-size: contain;" alt="It's Bill Murray.">
</div>

From MDN:

contain

A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color. The image is automatically centered unless over-ridden by another property such as background-position.

您是否尝试过在 .module-list-home .content .image-boundary-photo class 中设置 属性 background-size: contain;

要解决使用 background-size: contain; 时小图像也变​​得太大的问题,请使用百分比形式的大小。例如

.module-list-home .content .image-boundary-photo class 中设置 属性 background-size:60%; 而不是包含,我认为您的问题将得到解决。

希望对您有所帮助。

[编辑]

还编写了 jquery 动态检查图像大小和调整的解决方案。 这是 jquery 解决方案: http://codepen.io/Nasir_T/pen/ZpVbJo 。确保您的页面有 jquery.min 链接。

试试这个

$('.img-responsive').each(function(key, el) {
    var img = new Image;
    img.src = $(el).css('background-image').match(/^url\("?(.+?)"?\)$/)[1];
    if ($(el).width() <= img.width || $(el).height() <= img.height)
        $(el).css('background-size', 'cover');
})

这是一个working example