【问题标题】:scale background image in div depending on screen size根据屏幕大小在 div 中缩放背景图像
【发布时间】:2023-04-03 16:19:01
【问题描述】:

我有一个包含背景图像的 div,我想在右下角保持对齐,但我希望图像根据浏览器窗口的大小进行缩放。我目前拥有的是:

backgnd {
    background: url(img/roneggler.png) no-repeat;
    position: fixed;
    bottom: 0px;
    right: 0px;
    width: 1000px;
    height: 1000px;
}

我尝试将widthheight 值设置为100%,但这与div 的位置不一致。该页面的链接可以在这里找到:http://inetgate.biz/ron.eggler/

【问题讨论】:

    标签: html css background-image scale


    【解决方案1】:

    你应该使用 background-size: cover and width and height 100%;

    backgnd {
        background: url(img/roneggler.png) no-repeat;
        position: absolute;
        background-size: cover;
        bottom: 0px;
        right: 0px;
        width: 100%;
        height: 100%;
    }
    

    【讨论】:

    • 如果我使用你的建议,图像不是底部对齐的。
    • 尝试使用绝对位置(而不是固定位置)..并最终设置正确的右下位置
    • 是的,我正在使用absolute,正如您上面建议的那样。看起来 div 可以很好地缩放,但背景图像没有保持对齐 absolute 到 div 的右下角。我在 div 中添加了一个临时的 border: 5px solid red; 以更好地描绘事物
    • 你应该发布一个链接到 jsfiddle 或 codepen 以查看页面和代码..
    【解决方案2】:

    CSS:

    .container{
      width:100%;
    }
    

    你可以使用 jQuery:

    var w = $(window).width();
    $('.content').css('width', w);
    

    【讨论】:

      【解决方案3】:

      好的,

      我现在明白了,最终的解决方案如下:

      .backgnd {
          background: url(img/roneggler.png) no-repeat;
          background-size: contain;
          background-position: right bottom;
          position: absolute;
          bottom: 0px;
          right: 0px;
          width: 100%;
          height: 100%;
      }
      

      诀窍是不要使用background-size: contain; 而不是cover,以免图像在大屏幕上一直放大。

      【讨论】:

        猜你喜欢
        • 2016-06-20
        • 2014-06-21
        • 2013-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-16
        相关资源
        最近更新 更多