I don't fully understand how SVGs work yet. I know that viewBox have something to do with the scale of the SVG, and I have read that I shouldn't have specific height and width attributes when making a responsive SVG. I know there are a couple of questions about this here already, but as I don't understand them, I'm asking a bit more specific one.
I want to make a horizontal SVG line that changes length based on the width of the webpage.
I have been able to make a horizontal line with this code so far:
<svg id="horisontalLinje" width="500" height="5">
<line x1="0" y1="0" x2="500" y2="0"></line>
</svg>
CSS:
#horisontalLinje {
stroke: black;
stroke-width: 1;
}
The problem is as said that this line isn't responsive. What I want is this line to get a lower "width" based on the percentage of the width of the website the SVG is on. Like when using "vw" as a size in CSS.
CodePudding user response:
Well. I just figured it out... Just had to change the "width" to "x vw" and the "x2" to the same as the width.
CodePudding user response:
The vw
approach will work, unless someone is using a very old browser. Another, more traditional way is to use a viewBox
.
#horisontalLinje {
stroke: black;
stroke-width: 1;
}
<svg id="horisontalLinje" width="100%" height="1" viewBox="0 0 10 1" preserveAspectRatio="none">
<line x1="0" y1="0.5" x2="100" y2="0.5"></line>
</svg>
One other problem with your SVG is that the y
coordinates are 0. This means that half the line is off the top of the SVG viewport. The top (off-screen) half of the line is from -0.5 < y < 0, and the visible half is from 0 < y < 0.5. In other words, despite setting stroke-width
to 1. You are effectively only seeing a stroke of 0.5. You can fix that by setting the y
coordinates to 0.5.