【问题标题】:Relative DIV width and height相对 DIV 宽度和高度
【发布时间】:2015-01-09 07:21:53
【问题描述】:

我想要一个 DIV,最大 90% 高度或 90% 宽度。我只想将图片作为背景放入 DIV 中,并且应该可以看到完整的 svg 图像。在移动设备上以及在桌面上。

CSS:

.camera {
    position:absolute;
    background-image: url(../img/svg-bild.svg);
    background-repeat: no-repeat;
    background-position: center;
    max-height: 90%;
    max-width: 90%;
}

感谢您的帮助。

ps:我用谷歌但找不到有用的东西。我知道它会在某个地方,但我需要更少的时间来搜索 2 小时。

【问题讨论】:

    标签: html css image svg width


    【解决方案1】:

    如果您不希望背景图像被裁剪并始终适合容器,您可以使用background-size: contain; (more info on MDN)

    您还需要将 max-width/max-height 更改为 height/width 否则您的元素将具有 0 高度/宽度,因为它不包含任何内容:

    .camera {
        position:absolute;
        background-image: url(../img/svg-bild.svg);
        background-repeat: no-repeat;
        background-position: center;
        background-size:contain; /** add this **/
        height: 90%;  /** change this **/
        width: 90%;  /** change this **/
    }
    

    【讨论】:

    • 这个醒得很好 :) 谢谢老兄!我不能投票给你,因为我的排名很低......我会尽可能地这样做;)¨
    • @Patrick 很高兴我能提供帮助。如果您的问题已解决,请不要在您的问题标题中添加“已关闭”,只需单击解决您问题的 asnwser 旁边的勾号即可。
    • 不能完全满足手头问题的要求。无法保证图像是方形的,因此容器不会保存图像的尺寸 - 只会创建一个方形块。就是说,没有尺寸可以玩,这和它一样好。也许如果 OP 提供了更多关于正在使用的内容(肯定是 jQuery、CSS 和 HTML)的信息,比如 PHP 或类似的东西,你可以预先加载大小来满足要求。
    • @MrMarlow 这不需要创建一个方形块。块的尺寸将取决于相对定位的父级的尺寸。 background-size 属性将保证图像不会被裁剪,与块/图像大小/纵横比无关。
    【解决方案2】:

    jsBin demo

    .camera {
        position: absolute;
        background: url(../img/svg-bild.svg) 50% / cover;
        height: 90%;
        width: 90%;
        /*margin:auto;top:0;right:0;bottom:0;left:0; /* UNCOMMENT TO CENTER */
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用background-size:coverbackground-size:contain

      .camera {
      background-size:cover;/*background-size:contain;*/
      position:absolute;
      background-image: url(../img/svg-bild.svg);
      background-repeat: no-repeat;
      background-position: center;
      max-height: 90%;
      max-width: 90%;
      }
      

      【讨论】:

      • 问题是,图像没有出现,DIV 的宽度和高度为 0x0px...
      • @Patrick 将 max-height 更改为 min-height 或只是 height 并为宽度也这样做
      • background-size:cover 将裁剪图像。
      • @web-tiki ok 会像你说的那样做background-size: contain;
      • @Patrick 试试我说的,如果你想不剪裁的话,把background-size:cover改成background-size:contain
      猜你喜欢
      • 2012-06-03
      • 1970-01-01
      • 2015-07-17
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 2013-05-08
      相关资源
      最近更新 更多