相对于自己的大小缩放背景图像?

时间:2014-06-29 14:45:14

标签: css background-image scale

我有一个div,我已将背景设置为某个图像。例如,假设div为300x300,原始背景图片大小为200x200。

我想将背景图像相对于自身缩放一定百分比。例如,如果我要缩放200%,我希望背景图像现在是400x400像素,并略微切断。但我唯一能找到的css属性是background-size属性,它以相对于父div的百分比来缩放(例如,200%缩放,背景图像将变为600x600)。 / p>

有没有办法实现相对于背景图像本身的缩放?

3 个答案:

答案 0 :(得分:1)

所以我实际上找到了一种使用纯粹css的方法。我当然遇到的问题是,background-size相对于我们设置背景的div进行缩放,而不是图像大小本身。

解决方法是我们可以使用我们想要的宽度和高度将div包装在父div中,然后将内部div的宽度和高度设置为等于我们正在使用的背景图像的宽度和高度。这样我们可以根据背景的大小来缩放内部div,因为它们的大小相等,然后通过将父级设置为overflow:hidden来裁掉正确的数量。

*唯一的问题是我们必须使用服务器端渲染将内部div的宽度和高度设置为图像的宽度和高度,而不使用javascript。

例如:

<div style="width: 300px; height: 300px; overflow: hidden;">
    <div style="width:{{bgimgwidth}}; height:{{bgimgheight}}; background: url('{{url}}'); background-size: 200%;">
    </div>
</div>

答案 1 :(得分:0)

您可以使用 JavaScript

执行此操作

请参阅此JSFiddel ...(Source

HTML

<div id="box"></div>

CSS

#box{
    background: #fff center no-repeat;
    background-image: url(http://images2.layoutsparks.com/1/84256/batman-logo-black.jpg);
    width: 500px;
    height: 500px;
}

的JavaScript

window.onload = function() {
    var img = document.getElementById('box'),
    style = img.currentStyle || window.getComputedStyle(img, false),
    bi = style.backgroundImage.slice(4, -1);

    var imageSrc = bi.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];     

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    document.getElementById('box').style.backgroundSize = (width * 2.00) + 'px ' + (height * 2.00) + 'px'; 
}

希望这会对你有帮助..

答案 2 :(得分:-2)

在这种情况下,您可以设置background-size: 67%;。所以背景图像是父div的67%。

  • div 300x300,backgorund 201x201
  • div 600x600,backgorund 402x402

问候