简体   繁体   English

如何缩放背景图像以适合自适应div

[英]How to scale background-image to fit responsive div

I'm trying to make a "Did you know?" 我正在尝试发出“您知道吗?” fixed div in the right corner. 将div固定在右上角。 Unfortunately after 3 hours of testing many solutions still can't find correct one. 不幸的是,经过3个小时的测试,许多解决方案仍然找不到正确的解决方案。 As you can see on this fiddle: http://jsfiddle.net/dq8f3d4p/ I can't make the background fit the div. 正如您在此提琴上看到的那样: http : //jsfiddle.net/dq8f3d4p/我无法使背景适合div。

Both: background-size: cover; 两者: background-size: cover; and background-size: 100%; background-size: 100%; seems not to work properly. 似乎无法正常工作。

In your code, you are overwriting background-size with the shorthand background property : 在您的代码中,您将使用简写background属性覆盖background-size

.dyk{
    position: fixed;
    z-index:2;
    width: 17.26%;
    height: 11%;
    left: 80%;
    top: 80%;
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url(http://i.imgur.com/gxp9iDV.png);
}

Changing it to background-image property will cause the image to stretch to 100% size. 将其更改为background-image属性将导致图像拉伸到100%的大小。

You are probably looking for background-size:contain; 您可能正在寻找background-size:contain; , Which is usually the best pick, however, in your case the image proportions and the div's proportions are not the the same so I would recommend using background-size: 100% 100%; ,这通常是最佳选择,但是,在您的情况下,图像比例和div比例不相同,因此我建议使用background-size: 100% 100%; .

    background: url(http://i.imgur.com/gxp9iDV.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;

Working jsFiddle 工作jsFiddle

Notes: 笔记:

  1. background-size is supported by IE9+ IE9 +支持background-size
  2. Use contain if you don't want your image to get streched. 如果您不希望图像过分拉伸,请使用“ contain

put the image inside you div and then fix the div to bottom right 将图像放在div内,然后将div固定在右下角

<div class="dyk">
    <img src="http://i.imgur.com/gxp9iDV.png"></img>
</div>

.dyk{
    position: fixed;
    z-index:2;
    right: 0;
    bottom: 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM