这是一个代码演示
我有一个未知高度的SVG.在我加载json并使用javascript + math之后我可以弄明白但是有没有我可以用来动态调整大小的CSS?
CSS:
svg {
width: 500px;
height: 9000px;
}
.tabme {
border:3px solid red;
height: 200px;
overflow:scroll;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div class="tabme">
<div id="Chart">
<div class="chartbody" />
<svg>
<rect width="190" y="0" height="16" x="175" />
<rect width="190" y="20" height="16" x="175" />
<rect width="190" y="40" height="16" x="175" />
<rect width="190" y="60" height="16" x="175" />
<rect width="190" y="80" height="16" x="175" />
<rect width="190" y="100" height="16" x="175" />
<rect width="190" y="120" height="16" x="175" />
<rect width="190" y="140" height="16" x="175" />
<rect width="190" y="160" height="16" x="175" />
<rect width="190" y="180" height="16" x="175" />
<rect width="190" y="200" height="16" x="175" />
<rect width="190" y="220" height="16" x="175" />
<rect width="190" y="240" height="16" x="175" />
<rect width="190" y="260" height="16" x="175" />
<rect width="190" y="280" height="16" x="175" />
<rect width="190" y="300" height="16" x="175" />
</svg>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Tho*_*s W 15
如果SVG元素没有任何宽度和高度属性,则应根据CSS规范计算宽度/高度,如Robert Longson所指出的.但是,这些值不会反映SVG内容的正确尺寸.您可以使用以下方法找到合适的宽度/高度getBBox():
// Javascript to run after document load
var svg = document.getElementsByTagName("svg")[0];
var bbox = svg.getBBox();
svg.setAttribute("width", bbox.width + "px");
svg.setAttribute("height", bbox.height + "px");
svg.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);Run Code Online (Sandbox Code Playgroud)
<svg xmlns="http://www.w3.org/2000/svg" style="background-color: red">
<rect x="30" y="40" width="50" height="60"/>
</svg>Run Code Online (Sandbox Code Playgroud)