How can I align text vertically with SVG with cross browser compatibility?
Pay attention to the following snippet:
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
alignment-baseline = "middle"
text-anchor = "middle">
a
</text>
</svg>
Chrome renders this snippet as:
Whereas in FireFox this is the result:
How do I copy this snippet using a cross browser?
source to share
align-baseline is not supported by Firefox. Try using the dominant-base attribute , it should work for both (Chrome and Firefox, but not IE, see below).
Have a look at this old answer
According to the SVG specification, align-baseline applies only to "tspan", "textPath", "tref", and "altGlyph". I understand that it is used to compensate for those of the "text" object above them. I think what you are looking for is dominant-basic.
It works for Chrome and Firefox, but not IE. If you also want to have vertically oriented text in IE, you need to use the "arournd" function:
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
id = "default-text"
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
alignment-baseline = "middle"
dominant-baseline = "middle"
text-anchor = "middle">
a
</text><script>
window.onload = function() {
var text = document.getElementById("default-text"),
bbox = text.getBBox(),
actualHeight = (4 - bbox.y),
fontSize = parseInt(window.getComputedStyle(text)["fontSize"]),
offsetY = (actualHeight / 2) - (bbox.height - fontSize);
text.setAttribute("transform", "translate(0, " + offsetY + ")");
}
</script>
source to share
The simplest cross-browser solution is to use an attribute dy
with a value em
.
As long as the font is the same (it would be better to choose a specific font rather than a generic one like "monospace"), this trick should work for any font size.
<svg style="" width="60" height="60">
<rect
x = "0"
y = "0"
rx = "1"
ry = "1"
width = "17"
height = "15"
fill = "rgb(254,199,186)"
stroke = "rgb(152,119,111)"
stroke-width = "1">
</rect>
<text
x = "8"
y = "8"
fill = "rgb(50,39,37)"
font-size = "16"
font-family = "monospace"
text-anchor = "middle"
dy = "0.25em">
a
</text>
</svg>
source to share
Firefox prior to version 40 does not support the midpoint of the dominant baseline properly (it treats it as centerline), and neither version supports baseline alignment.
I'm afraid the alignment implementation - baseline and dominant-baseline is a bit of a minefield at this time, as IE does not support SVG text, nor Firefox only supports dominant baseline, and its implementation of this property is not quite consistent with Chrome.
source to share