SVG中的文本对齐方式不适合我们习惯于HTML和CSS的方式,在HTML和CSS中,一切都是具有一定尺寸的盒子,我们可以应用例如text-align: center
。
在<svg:text>
中,起始坐标定义点将从其展开文本行。
text-anchor
属性控制此扩展将发生的方向:center
值表示它将双向扩展,因此初始锚点将位于边界框宽度的中间(对于水平书写系统)。请参见出色的答案,说明此text-anchor
是将文本居中SVG的最佳方式:https://stackoverflow.com/a/23272367/540955。另外,SVG内没有CSS位置属性(左/上),只有x / y坐标,也没有空白和余量,就像您在HTML中所知道的那样。
因此,在您的代码中添加text-anchor="middle"
并向右移动x
坐标将产生居中文本。我建议使用裸露的<text>
元素而不是<tspan>
,因为用dx
/ dy
进行移位是相对于最后一个前一个字符,并且该字符可能是父<text>
的一些空格(取决于代码格式)会导致不平衡的居中。为了简化计算,dominant-baseline
="central"
(或者对于水平书写系统仅为middle
)很有用,因为它将锚点从基线移动到“中心线”。
因此,使用dy
属性(如您已经做的那样)将行高的第一行“一半”向上移动,另一行向下移动,应该可以解决问题:
<svg viewBox="0 0 800 200" text-anchor="middle" dominant-baseline="central" font-size="100">
<!-- Outline and diagonals with center point for illustration: -->
<path d="M0,0h800v200h-800zl800,200m0 -200L0,200" fill="#FC9" stroke-width="1" stroke="rgba(0,0.3)"></path>
<circle cx="50%" cy="50%" r="10" fill="red"></circle>
<!-- Centered text: -->
<text x="50%" y="50%" fill="rgba(0,0.3)">So</text>
<!-- Shifted up and down: -->
<text x="50%" y="50%" dy="-0.5em">So</text>
<text x="50%" y="50%" dy="+0.5em">Food</text>
</svg>
(不完全相关:仅可以使用background-clip: text
在CSS中进行剪辑;这是您设计的粗略变化,因为它出现在Chrome浏览器中,带有动画文本背景,但没有阴影。不幸的是添加阴影会我认为需要更多的元素或属性。这应该在任何支持background-clip的浏览器中都可以使用。)
div {
display: flex;
flex-direction: column;
align-items: center;
font-size: 30vh;
line-height: 30vh;
font-weight: bold;
font-family: Impact;
}
span {
color: #fff;
background-color: #000;
width: 100%;
text-align: center;
}
@supports (-webkit-text-fill-color: transparent) and (-webkit-background-clip: text) {
span {
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
animation: 2s wohoo infinite alternate cubic-bezier(1,1,1);
background-position: 0 0;
background-size: 100% 100%;
background-color: transparent;
background-image: linear-gradient(
to right,#f2385a 0,#f2385a 20%,#f5a503 0,#f5a503 40%,#e9f1df 0,#e9f1df 60%,#56d9cd 0,#56d9cd 80%,#3aa1bf 0,#3aa1bf 100%
);
background-repeat: no-repeat;
transform-origin: center center;
}
}
@keyframes wohoo {
from {
background-size: 0 100%;
background-position: -5vh 0;
transform: scale(0.7);
}
50% {
transform: scale(0.7);
}
90% {
transform: scale(0.9);
}
to {
background-size: 500% 100%;
background-position: 0vh 0;
transform: scale(0.9)
}
}
html,body{margin:0;overflow:hidden;}
body {
background-color: #1d1f20;
color: snow;
display: flex;
flex-direction: row;
justify-content: center;
width: 100%;
}
<div>
<span>Baz</span>
<span>Gazonk</span>
<span>Qux</span>
</div>
本文链接:https://www.f2er.com/3100303.html