MathML中分数平方根的根号尾部过度延伸问题求助
解决MathML根号尾部超出分数分母的布局问题
通常MathML显示根号时,尾部会与根号内容的底部对齐:
但当对分数取平方根时,根号尾部会远远超出分母:
相关代码:
<svg height="160" width="160" viewBox="0 0 160 160" xmlns="http://www.w3.org/2000/svg"> <foreignObject height="120" width="120" x="20" y="20"> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML"> <msqrt> <mfrac> <mrow> <mi>P</mi> </mrow> <mrow> <mi>R</mi> </mrow> </mfrac> </msqrt> </math> </foreignObject> </svg>
移除display="block"会导致分子、分母字号缩小,不符合需求。制作图表时这个问题严重影响布局,要么单独缩小该公式字号,要么把其他公式调小来匹配,查阅MathML Core文档后未找到解决方案,以下是可行调整方法:
可行解决方案
1. 用CSS变量控制根号延伸长度
针对msqrt元素,通过--math-radical-extension变量(主流浏览器基本支持)直接调整根号尾部的延伸长度:
<svg height="160" width="160" viewBox="0 0 160 160" xmlns="http://www.w3.org/2000/svg"> <foreignObject height="120" width="120" x="20" y="20"> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML" style="--math-radical-extension: 0.5em;"> <msqrt> <mfrac> <mrow> <mi>P</mi> </mrow> <mrow> <mi>R</mi> </mrow> </mfrac> </msqrt> </math> </foreignObject> </svg>
若浏览器不支持该变量,可给msqrt套一个裁剪容器:
<svg height="160" width="160" viewBox="0 0 160 160" xmlns="http://www.w3.org/2000/svg"> <foreignObject height="120" width="120" x="20" y="20"> <div style="overflow: hidden; display: inline-block; vertical-align: middle;"> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML"> <msqrt> <mfrac> <mrow> <mi>P</mi> </mrow> <mrow> <mi>R</mi> </mrow> </mfrac> </msqrt> </math> </div> </foreignObject> </svg>
2. 用mpadded限制分数垂直范围
给分数外层添加mpadded标签,通过height和depth属性限制分数的整体垂直高度,让根号尾部不会过度延伸:
<svg height="160" width="160" viewBox="0 0 160 160" xmlns="http://www.w3.org/2000/svg"> <foreignObject height="120" width="120" x="20" y="20"> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML"> <msqrt> <mpadded height="1.2em" depth="0.4em"> <mfrac> <mrow> <mi>P</mi> </mrow> <mrow> <mi>R</mi> </mrow> </mfrac> </mpadded> </msqrt> </math> </foreignObject> </svg>
可根据实际显示效果微调height和depth的数值,直到根号尾部与分母底部对齐。
3. 用CSS缩放保持字号比例
如果上述方法无效,可保留display="block",通过外层容器的transform: scale()整体缩小公式,同时用transform-origin调整位置避免布局偏移:
<svg height="160" width="160" viewBox="0 0 160 160" xmlns="http://www.w3.org/2000/svg"> <foreignObject height="120" width="120" x="20" y="20"> <div style="transform: scale(0.8); transform-origin: top left; display: inline-block;"> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML"> <msqrt> <mfrac> <mrow> <mi>P</mi> </mrow> <mrow> <mi>R</mi> </mrow> </mfrac> </msqrt> </math> </div> </foreignObject> </svg>
这种方法能精准控制公式整体大小,同时保持分子分母的字号比例不变。
内容的提问来源于stack exchange,提问作者agtl
相关产品推荐
相关产品推荐

