如何在svg中居中图像

Mat*_*att 5 html css svg

我有一个图像 svg 元素,它可以有任何宽度。我想在 svg 元素或 div 容器中水平居中图像。我试过margin: 0 auto;text-align : center;但它不起作用。

提琴手

html

<div class="background-img" style="width: 100px; height: 110px;">
   <svg class="svg-defs" width="100px" height="110px">
      <defs>
         <clipPath id="clip-triangle-10">
            <polygon points="0,0 110,0 110,100 19,100 12,107 5,100 0,100 0,0"></polygon>
         </clipPath>
      </defs>
      <rect class="svg-background" clip-path="url(#clip-triangle-10)" width="100px" height="110px"></rect>
      <image class="svg-image" clip-path="url(#clip-triangle-10)" height="100px" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://upload.wikimedia.org/wikipedia/en/thumb/6/6c/Seafarers_title.jpg/225px-Seafarers_title.jpg"></image>
   </svg>
</div>
Run Code Online (Sandbox Code Playgroud)

<div class="background-img" style="width: 100px; height: 110px;">
   <svg class="svg-defs" width="100px" height="110px">
      <defs>
         <clipPath id="clip-triangle-10">
            <polygon points="0,0 110,0 110,100 19,100 12,107 5,100 0,100 0,0"></polygon>
         </clipPath>
      </defs>
      <rect class="svg-background" clip-path="url(#clip-triangle-10)" width="100px" height="110px"></rect>
      <image class="svg-image" clip-path="url(#clip-triangle-10)" height="100px" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://upload.wikimedia.org/wikipedia/en/thumb/6/6c/Seafarers_title.jpg/225px-Seafarers_title.jpg"></image>
   </svg>
</div>
Run Code Online (Sandbox Code Playgroud)
image{
 position: relative;
  display: block;
  margin: 0 auto;
  text-align : center;
}
Run Code Online (Sandbox Code Playgroud)

小智 4

我不确定仅通过 HTML 和 CSS 以及来自外部图像的图像宽度是否可以实现这一点。如果您愿意使用一些 JavaScript,那么这可能是一个可能的解决方案:

var svgImage = document.querySelectorAll('.svg-image');

Array.prototype.forEach.call(svgImage, function(el, i){
  var xOffset = '-' + ((Math.floor(el.getBoundingClientRect().width)) - 100) / 2
  el.setAttribute('x', xOffset);
});
Run Code Online (Sandbox Code Playgroud)

该循环遍历每个.svg-image,然后计算将图像在 100 像素宽的显示屏中居中所需的偏移量。

可以在JSFiddle上看到它的运行情况