【问题标题】:How do I fit svg to html width and height?如何使 svg 适合 html 的宽度和高度?
【发布时间】:2017-10-17 04:36:25
【问题描述】:

我想创建一个只包含一个svg 元素的页面,该元素适合宽度和高度并具有最大可能的比例。

【问题讨论】:

    标签: html css svg


    【解决方案1】:

    这可能会有所帮助。我使用这个 CSS 来调整背景图像的宽度和高度,并根据浏览器相应地缩小。

    html { 
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      position: relative;
    }
    

    您可以在 DIV 中设置您的 SVG 并为其添加一个类,然后您只需使用上述 CSS 来缩放 DIV 的内容。

    【讨论】:

      【解决方案2】:

      将你的图片放在一个 div 中,并应用这些 css 规则:

      div{
        height:100vw;
        height:100vh;
      }
      svg{
        height:100%;
        width:100%
      }
      

      【讨论】:

      • 不幸的是,这只是裁剪 svg
      【解决方案3】:

      相关问题

      How can I make an svg scale with its parent container?

      How to resize an image to fit in the browser window?

      没有用,但是结合所提出的方法解决了这个问题。

      1) 将打开<svg ...> 标记中的width="A" height="B" 替换为viewBox="0 0 A B" max-width="100%" width="auto" max-height="100vh" height="auto"

      现在它几乎可以工作但不是很准确,因为浏览器会自动将margin: 8 添加到body 的样式(即使.html 文件中没有<body> 标签)。所以

      2) 添加<style> body { margin: 0 } </style>

      【讨论】:

        猜你喜欢
        • 2016-09-11
        • 2019-11-24
        • 2017-12-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2016-04-15
        • 2016-06-15
        相关资源
        最近更新 更多