SVG元素无法放置在一个DIV内

5
我正在尝试在 div 中显示一个 svg 线条。DIV 已经给定了位置,所以我希望线条作为子元素放置在 div 内部,但它却出现在 div 外部。以下是我的代码:
<div style="position:absolute; top:246pt; left:6pt; width:581.976pt; height:3pt; border:1px solid blue"> 
    <svg xmlns="http://www.w3.org/2000/svg"  version="1.1" width="581.976pt" height="3pt" style="border:1px solid black">
        <line id = "default" x1="0pt" y1="1.5pt" x2="581.976pt" y2="0pt" style="stroke:rgb(229,52,52); stroke-width:3pt;stroke-dasharray:10, 5"/> 
    </svg> 
</div> 

Fiddle

我一直在努力找到原因,但是无法理解这种行为。如有帮助,将不胜感激。谢谢。

3个回答

8
float:left;display: block;应用于SVG元素。

<div style="position:absolute; top:246pt; left:6pt; width:581.976pt; height:3pt; border:1px solid blue"> 
    <svg xmlns="http://www.w3.org/2000/svg"  version="1.1" width="581.976pt" height="3pt" style="border:1px solid black; float:left;">
    <line id = "default" x1="0pt" y1="1.5pt" x2="581.976pt" y2="1.5pt" style="stroke:rgb(229,52,52); stroke-width:3pt;stroke-dasharray:10, 5"/> 
    </svg> 
</div> 


1
谢谢,两种方法都可以。请问哪一种更好? - Abdul Jabbar
@AbdulJabbar 显示块可能更有意义,除非文本是要围绕它流动。 - Alexander O'Mara
两种方法都可以正常工作。但是正如@AlexanderO'Mara所说,display: block; 更合理。 - The Pragmatick

3

问题在于SVG溢出了 DIV,这主要是由于SVG元素默认情况下是display: inline ;。可以通过向SVG的样式添加一个显示属性(如display: block;)来轻松解决此问题。

<div style="position:absolute; top:246pt; left:6pt; width:581.976pt; height:3pt; border:1px solid blue"> 
    <svg xmlns="http://www.w3.org/2000/svg"  version="1.1" width="581.976pt" height="3pt" style="border:1px solid black; display: block;">
        <line id = "default" x1="0pt" y1="1.5pt" x2="581.976pt" y2="1.5pt" style="stroke:rgb(229,52,52); stroke-width:3pt;stroke-dasharray:10, 5"/> 
    </svg> 
</div>

在这种情况下,另一种选择是浮动或定位SVG元素,但这是一个不太灵活的解决方案,只能间接地解决问题。

0
将您的Div位置更新为“block”,并将您的svg元素浮动到“left”。 演示链接

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接