gpt4 book ai didi

jquery - 中心 SVG 图表宽度 jQuery

转载 作者:行者123 更新时间:2023-11-28 00:01:26 25 4
gpt4 key购买 nike

我正在尝试将 SVG 图表居中。目前它的 html 看起来像这样:

<div class="svgWrapper">
<svg>Generated svg chart</svg>
</div>

我无法为 SVG 指定宽度和高度,因为它采用响应式设计。我无法使用 jQuery 获取 SVG 宽度或高度

$('svg').width();

返回包装器 div 的宽度,但 svg 宽度不等于包装器宽度。

<div class="svgWrapper">
<div style="float: left;">
<svg>...</svg>
</div>
</div>

知道如何通过更改 SVG 和包装器的 w/h(包装器高度始终保持不变)在包装器 div 中将生成的 SVG 图表垂直和水平居中吗?

最佳答案

canvas 元素包裹在 div 中并分配 display: table-cell; 然后使用 vertical-align: middle ; 以及 text-align: center;垂直水平对齐

Demo

div {
display: table-cell;
height: 300px;
width: 300px;
vertical-align: middle;
text-align: center;
border: 1px solid #eee;
}

canvas {
height: 30px;
width: 30px;
border: 4px solid #f00;
}

不想使用 display: table-cell; ?你也可以使用 CSS 定位来实现这一点。在这里,我将 position: relative; 分配给容器元素,然后将子元素设为 position: absolute;,只需确保使用 margin: auto ; 因为它很重要。

Demo 2

div {
position: relative;
height: 300px;
width: 300px;
border: 1px solid #eee;
}

canvas {
height: 30px;
width: 30px;
border: 4px solid #f00;
position: absolute;
top: 0;
left: 0;
right: 0;
margin: auto;
bottom: 0;
}

Note: Am aware that the height and width of the canvas are dynamic, but I am just using fixed for demonstration purposes.

关于jquery - 中心 SVG 图表宽度 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com