gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:29:24 26 4
gpt4 key购买 nike

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

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

主要的 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.

关于javascript - 如何根据图像大小在 css 中添加背景大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com