I am trying to center text in an area based on some shapes.
In the example below, each square has a height and width of 50% of the SVG. I am trying to center the very large "X" character. Intuitively, I thought setting the text's x and y to the center of any square (25%,25% or 25%,75% or 75%,75% or 75%,25%), but it is off. I need to adjust the percentage a little more to center them.
In the example below, it looks like my intuition is wrong in the upper left square, whereas adjusting the y% a little centers it in the upper right square. The smaller blue and green squares are included to show exactly where 25%,25% and 25%,75% are.
I notice that this changes when font size changes as well. Is there a way to center text based on the font size using percentages? What key concept am I missing for understanding why this doesnt work?
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
<style>
.f{font-family:monospace;font-size:80pt}
</style>
<rect width="50%" height="50%" y="0%" fill="red"/>
<rect width="50%" height="50%" y="50%" fill="green"/>
<rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
<rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
<text x="25%" y="25%" class="f" dominant-baseline="middle" text-anchor="middle">X</text>
<text x="75%" y="29%" class="f" dominant-baseline="middle" text-anchor="middle" fill="blue">X</text>
<rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
<rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>
CodePudding user response:
The font allows for all characters to be displayed.
You need to change the baseline
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseline-shift
CodePudding user response:
Looks like you want dominant-baseline="central" rather than middle.
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
<style>
.f{font-family:monospace;font-size:80pt}
</style>
<rect width="50%" height="50%" y="0%" fill="red"/>
<rect width="50%" height="50%" y="50%" fill="green"/>
<rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
<rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
<text x="25%" y="25%" class="f" dominant-baseline="central" text-anchor="middle">X</text>
<text x="75%" y="29%" class="f" dominant-baseline="central" text-anchor="middle" fill="blue">X</text>
<rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
<rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>