我正在尝试生成一个 svg 矩形和一个 span,以便 span 元素中的文本与 svg 元素垂直对齐。在声明式 HTML+CSS 中,我设法做到了。 但我无法通过 javascript 做到这一点。
这是我的 javascript 代码:
/* Svg creation
==============================*/
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", 60);
svg.setAttribute("height", 60);
var square = document.createElementNS("http://www.w3.org/2000/svg", "rect");
square.setAttribute("x", 0);
square.setAttribute("y", 0);
square.setAttribute("width", 60);
square.setAttribute("height", 60);
square.setAttribute("fill", "red");
svg.appendChild(square);
document.body.appendChild(svg);
/* Span creation
==============================*/
var outerSpan = document.createElement("span");
outerSpan.style.height = "60px";
outerSpan.style.lineHeight = "60px";
var innerSpan = document.createElement("span");
innerSpan.style.display = "inline-block";
innerSpan.style.verticalAlign = "middle";
innerSpan.style.lineHeight = "1em";
innerSpan.textContent = "Red square";
outerSpan.appendChild(innerSpan);
document.body.appendChild(outerSpan);
在这里my codepen attempt : 您会注意到 html+css 代码有效,但 javascript 代码无效,我的意思是,它显示了所有内容,但不是我想要的。
最佳答案
那是因为 svg
元素的垂直对齐不是 middle
本身;它是 baseline
(默认)。这里的 svg
元素将自身与基线对齐,基线是文本的底部。
这可以通过简单地指定来解决:
svg.style.verticalAlign = "middle";
关于javascript动态创建跨度并垂直对齐文本: text stays at the bottom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32826534/