Html 在 div 中嵌套 svg

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15474306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:37:43  来源:igfitidea点击:

nesting an svg inside a div

htmlcsssvg

提问by RedBaron

I am trying to create a filled svg triangle which will be placed at someplace on the page.

我正在尝试创建一个填充的 svg 三角形,该三角形将放置在页面上的某个位置。

To accomplish this I wrap the svg in a div and place the div appropriately. However, the svg is always rendered outside of the div. How do I get the svg element rendered inside the div?

为了实现这一点,我将 svg 包装在一个 div 中并适当地放置 div。但是,svg 总是呈现在 div 之外。如何在 div 内渲染 svg 元素?

I can't use the <object>or the <embed>tag due to scripting and templating constraints

由于脚本和模板限制,我无法使用<object><embed>标记

Sample HTML

示例 HTML

<div id="container">
    <div id="inner_container">
        <svg height="6" width="6">
            <path d="M 0 6 L 3 0 L 6 6 L 0 6"/>
        </svg>
    </div>
</div>

And the CSS

和 CSS

#container {width:100px; height:25px; border:1px solid green;}
#container #inner_container {width:6px; height:6px; border:1px solid red;}
#inner_container  svg path {fill:black;}

The filled triangle should be inside the red rectangle but is rendered outside

实心三角形应该在红色矩形内,但呈现在外面

See it on JsFiddle

JsFiddle查看

采纳答案by Sowmya

Change the css selector, write only svg{...}and add float:left

更改css选择器,只写svg{...}并添加float:left

Here path is just a drawing not an element.

这里的路径只是一个绘图而不是一个元素。

svg {fill:black; float:left}

DEMO

演示

回答by Michael Giovanni Pumo

Try this:

尝试这个:

#container { float: left; width: 100px; height: 25px; border: 1px solid green; }
#container #inner_container { float: left; width: 6px; height: 6px; border: 1px solid red; }
#inner_container svg { display: block; float: left; }

I add some floats in there so that they 'contain' the elements. There are better and more elegant ways to do this, but it should work.

我在那里添加了一些浮点数,以便它们“包含”元素。有更好和更优雅的方法来做到这一点,但它应该有效。

Hope this helps. Mikey.

希望这可以帮助。米奇。

回答by yegor256

The problem is that you didn't specify namespace for svgelement. This is how it works:

问题是您没有为svg元素指定命名空间。这是它的工作原理:

<div id="container">
  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 100 100">
    <path d="M 0 6 L 3 0 L 6 6 L 0 6"/>
  </svg>
</div>