我有一个图像svg元素,它可以有任何宽度。我想在svg元素或div容器中水平居中放置图像。我试过margin: 0 auto;
或text-align : center;
但它不起作用。如何在svg中居中图像
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>
image{
position: relative;
display: block;
margin: 0 auto;
text-align : center;
}
<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>
我想避免这种解决方案,但也许没有其他办法。我会让这个问题开放1-2天。如果没有其他解决方案,我会接受这个答案。谢谢。 – Matt
我想不出另一种方式。纯粹是因为图像尺寸可能会发生变化,并且需要针对每个人进行计算。 – 2017-10-18 10:12:01
我认为你是对的。 – Matt