I want a html page title centered with a curve to it using SVG, CSS and HTML. The first letter should be the same height on the page as the last letter so it forms a half oval shape with the middle of the text elevated.
The closest I got was:
<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
<path id="MyPath" fill="none" stroke="red" d="M100,200
Q250,100 400,200" />
<text >
<textPath href="#MyPath" startOffset="80">
Curved Title
</textPath>
</text>
</svg>
The red line doesn't need to be there, I only want the text.
I would like to have content below the SVG without a big gap, currently it pushes other elements in the div half way down the page with blank space.
I've looked at examples on stack overflow and the web, most of the text is either a full circle or text is uneven with the start or end of the title hanging lower or with an uneven shape. I want to be able to center it in a div with dynamic width.
CodePudding user response:
First of all you can use text-anchor
in combination with pathLength
and startOffset
to place the text in the middle. Here the the path length is 2, so the start offset is 1 and the anchor is set to "middle".
Second I changed the path a bit; scaled it and placed it in the top of the SVG (the arch hits y=0 in the middle). It is still the same shape. I used dominant-baseline
to let the text "hang" under the path.
Now the viewbox can be scaled as well. If it has the height of 5 you can see the entire path, bit if you set it to 3 (second example) the following content will move closer.
An alternative could be to place the SVG as part of the CSS as a background in the content.
svg {
display: block;
}
<svg viewBox="0 0 30 5" xmlns="http://www.w3.org/2000/svg">
<path id="MyPath" fill="none" stroke="red" stroke-width=".1" d="M 0 5 Q 15 -5 30 5" pathLength="2" />
<text font-size="2" dominant-baseline="hanging" text-anchor="middle">
<textPath href="#MyPath" startOffset="1">
Curved Title
</textPath>
</text>
</svg>
<div style="background:silver">More content</div>
svg {
display: block;
}
<svg viewBox="0 0 30 3" xmlns="http://www.w3.org/2000/svg">
<path id="MyPath" fill="none" stroke="red" stroke-width=".1" d="M 0 5 Q 15 -5 30 5" pathLength="2" />
<text font-size="2" dominant-baseline="hanging" text-anchor="middle">
<textPath href="#MyPath" startOffset="1">
Curved Title
</textPath>
</text>
</svg>
<div style="background:silver">More content</div>