Reputation: 43481
i'm trying to center SVG chart. Currently it's html looks like this:
<div class="svgWrapper">
<svg>Generated svg chart</svg>
</div>
I can't specify width and height for SVG, because it's in responsive design. I can't get SVG width or height with jQuery
$('svg').width();
returns width of wrapper div, but svg width is not equal to wrapper width.
<div class="svgWrapper">
<div style="float: left;">
<svg>...</svg>
</div>
</div>
Any idea how to center that generated SVG chart verticaly and horizontaly in wrapper div with changing w/h of SVG and wrapper (wrapper height always stays the same)?
Upvotes: 2
Views: 660
Reputation: 157324
Wrap your canvas
element inside a div
and assign display: table-cell;
and than use vertical-align: middle;
as well as text-align: center;
to align vertically as well as horizontally
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;
}
Don't want to use display: table-cell;
? Than you can also achieve this using CSS Positioning. Here, am assigning position: relative;
to the container element, and than am making the child element position: absolute;
, just make sure you use margin: auto;
there as it's crucial.
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
andwidth
of thecanvas
are dynamic, but I am just using fixed for demonstration purposes.
Upvotes: 2