SVG 元素不在 DIV 内

SVG element not coming inside a DIV

我正在尝试在 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

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

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> 

问题是 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 元素,但这是一个不太通用的解决方案,只能间接解决问题。

将您的 Div 位置更新为 block 并将您的 svg 元素浮动为 left

working Demo