Hi everyone,
I’m working on dynamically generating SVG graphs using PHP, and I’m encountering an issue when trying to make them responsive. I’ve followed the advice on (view.sitepoint.com/make-responsive-svg-graphs-infographics/) and set the viewBox to make the SVG scalable. However, when the graph is resized, it doesn’t scale properly and some elements, like text, don’t adjust accordingly.
Here’s a simplified version of my PHP code that generates the SVG:
<?php
$width = 500;
$height = 500;
echo '<svg width="100%" height="100%" viewBox="0 0 ' . $width . ' ' . $height . '" xmlns="http://www.w3.org/2000/svg">';
echo '<rect width="100%" height="100%" fill="#f0f0f0" />';
echo '<circle cx="250" cy="250" r="100" fill="#007bff" />';
echo '<text x="250" y="250" text-anchor="middle" fill="#ffffff" font-size="20">Graph</text>';
echo '</svg>';
?>
I have set the width
and height
to 100%, and I’m dynamically setting the viewBox
attributes based on the $width
and $height
variables.
However, when I scale down the browser window, the circle and text elements don’t resize properly. The text stays too large, and the circle is cut off. I also tried adding some CSS media queries to adjust the text size:
@media (max-width: 500px) {
svg {
width: 100%;
height: auto;
}
text {
font-size: 15px;
}
}
he issue is still present, and I’m wondering if it’s something related to how PHP generates the SVG dynamically or if it’s an issue with the scaling logic.
Has anyone faced this problem before? I would really appreciate some guidance on how to get the text and elements to scale properly in responsive views.
Thanks!