如何将SVG叠加层固定在容器内的图像上?

时间:2017-07-07 10:57:29

标签: html css svg

我正在尝试使背景图像和SVG响应。我把它们放在一个容器中,两者都是从他们自己的角度来回应的。但是当我通过拉伸浏览器来测试它时,SVG会被取代。我需要在背景图像上修复SVG叠加层,它们将被放置在我设置它们的图像的位置。



<!DOCTYPE html>
<html>

<head>
    <style>
        .container {
            background: url(http://i.imgur.com/b1K76Pf.jpg) no-repeat;
            background-size: contain;
            max-width: 960px;
            height: 565px;
            margin: auto;
        }
        
    </style>
</head>

<body>

    <div class="container">
        <div class="main-roof">
            <svg width="100%" height="100%" viewbox="0 0 1200 180" 
preserveAspectRatio="none">

<polygon fill="red" points="115,103 643,93 930,47 372,72">
</polygon>	
<polygon fill="red" points="30,120 170,112 649,105 513,118 ">
</polygon>
<polygon fill="red" points="610,49 642,57 600,56 576,57">
</polygon>	
            </svg>
         </div>
      </div>
  </body>
</html>
&#13;
&#13;
&#13;

P.S。我尝试了.container宽度和高度%auto,但在这种情况下,图片不会显示。

1 个答案:

答案 0 :(得分:1)

所以为了结束这个问题,我将我们的评论作为答案召开。


我无法重现您描述的行为。我做了一个小提琴:https://jsfiddle.net/aL7keb3u。我在FF54和Chrome59中运行它。在这两种浏览器中,SVG的大小与容器中的bg-image相同。

您想要一个SVG,它根据浏览器窗口进行缩放,但与(背景)图像的纵横比相同。无需设置绝对像素值,而是设置相对值。对?如果是这样,可能对您有所帮助:https://jsfiddle.net/aL7keb3u/4

<强> HTML:

<div class="container">
  <img src="http://i.imgur.com/b1K76Pf.jpg" class="bg_image" />
  <div class="main-roof">
    <svg width="100%" height="100%" viewbox="0 0 1200 180" 
         preserveAspectRatio="none">

      <polygon fill="red" points="115,103 643,93 930,47 372,72">
      </polygon>    
      <polygon fill="red" points="30,120 170,112 649,105 513,118 ">
      </polygon>
      <polygon fill="red" points="610,49 642,57 600,56 576,57">
      </polygon>    
    </svg>
  </div>
</div>

<强> CSS:

.container {
  /*background: url(http://i.imgur.com/b1K76Pf.jpg) no-repeat;*/
  /*background-size: contain;*/
  max-width: 960px;
  /*height: 565px;*/
  margin: auto;
  position: relative;
}

/* ---------------------- */

.container > img.bg_image {
    width: 100%;
    height: auto;
}

.main-roof {
    max-width: 100%;
    max-height: 100%;
    overflow: hidden;

    mix-blend-mode: multiply; /* nice effect */

    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
svg {
    /*height: 565px;*/
    width: 100%;
    height: 103.5%;
}


正如您自己所说,问题是由于HTML无效。当您遇到(无法解释的)问题时,请先验证您的HTML。