使用 "vw" 获得 100% 宽度的标题
Using "vw" to get 100% width headings
我有一个 h1 我想适应视口的整个宽度,它由 13 个字符组成,采用 monospaced 字体。在阅读了关于视口大小排版的 CSS-Tricks 文章之后,从逻辑上讲,如果我想实现这一点,我只需将 h1 的样式设置为:
h1 {
font-size: 13vw;
font-family: monospace;
}
然而,这是渲染时留下了一点 space(突出显示文本以查看白色 space):
(There would be an image here but I don't have enough rep so click here for the JSFiddle)
试过其他尺码,font-size: 14vw;
有点大,font-size: 13.99vw;
好像刚刚好,奇怪的是font-size: 13.999vw;
还是太大了?
谁能解释一下这是怎么回事?为什么 monospaced 字体中 13 个字符长度的字符串中的每个字符需要 多于 (100/13)% 的视口宽度才能适应整个视口宽度?
问题是如果文本与父容器的大小完全相同,它将跨越第二行。
body {
margin: 0;
width:100px
}
h1 {
font-family: monospace;
width:100px;
}
这将导致文本换行,因为它们都是 100 像素。这就是为什么 14vw 太大了,但是 13.99 就足够了:Fiddle DEMO
但是,您可以使用 text-align: justify;
来实现您想要的。
看看这个Fiddle DEMO。
在开始之前,我只想说,由于 对 Stoyan Dekov 的回答,我不会为您提供解决方法。相反,我只会回答你的问题 有人能解释一下这里发生了什么吗?
font-size
!= width
这里的问题是您假设 font-size
与 width
相同。它不是。 CSS Fonts Module 将 font-size
定义为:
...the desired height of glyphs from the font.
这意味着 font-size
与 height
的可比性高于 width
。
这也不是特定于 vw
单元的。如果您以像素为单位指定 font-size
,您还会注意到计算出的 width
与 font-size
.
不匹配
但即便如此,这仍然取决于您使用的 font-family
,正如同一段继续说的那样:
For scalable fonts, the font-size is a scale factor applied to the EM unit of the font. (Note that certain glyphs may bleed outside their EM box.) For non-scalable fonts, the font-size is converted into absolute units and matched against the declared font-size of the font, using the same absolute coordinate space for both of the matched values.
这里的关键词是可扩展和不可扩展。
即使使用不可缩放的字体,13vw
也不会反映每个字符的 宽度。这永远不会与 vw
一起使用,但它可能与 vh
一起使用,但前提是每个单独字符的纵横比与屏幕的纵横比匹配。
我有一个 h1 我想适应视口的整个宽度,它由 13 个字符组成,采用 monospaced 字体。在阅读了关于视口大小排版的 CSS-Tricks 文章之后,从逻辑上讲,如果我想实现这一点,我只需将 h1 的样式设置为:
h1 {
font-size: 13vw;
font-family: monospace;
}
然而,这是渲染时留下了一点 space(突出显示文本以查看白色 space):
(There would be an image here but I don't have enough rep so click here for the JSFiddle)
试过其他尺码,font-size: 14vw;
有点大,font-size: 13.99vw;
好像刚刚好,奇怪的是font-size: 13.999vw;
还是太大了?
谁能解释一下这是怎么回事?为什么 monospaced 字体中 13 个字符长度的字符串中的每个字符需要 多于 (100/13)% 的视口宽度才能适应整个视口宽度?
问题是如果文本与父容器的大小完全相同,它将跨越第二行。
body {
margin: 0;
width:100px
}
h1 {
font-family: monospace;
width:100px;
}
这将导致文本换行,因为它们都是 100 像素。这就是为什么 14vw 太大了,但是 13.99 就足够了:Fiddle DEMO
但是,您可以使用 text-align: justify;
来实现您想要的。
看看这个Fiddle DEMO。
在开始之前,我只想说,由于
font-size
!= width
这里的问题是您假设 font-size
与 width
相同。它不是。 CSS Fonts Module 将 font-size
定义为:
...the desired height of glyphs from the font.
这意味着 font-size
与 height
的可比性高于 width
。
这也不是特定于 vw
单元的。如果您以像素为单位指定 font-size
,您还会注意到计算出的 width
与 font-size
.
但即便如此,这仍然取决于您使用的 font-family
,正如同一段继续说的那样:
For scalable fonts, the font-size is a scale factor applied to the EM unit of the font. (Note that certain glyphs may bleed outside their EM box.) For non-scalable fonts, the font-size is converted into absolute units and matched against the declared font-size of the font, using the same absolute coordinate space for both of the matched values.
这里的关键词是可扩展和不可扩展。
即使使用不可缩放的字体,13vw
也不会反映每个字符的 宽度。这永远不会与 vw
一起使用,但它可能与 vh
一起使用,但前提是每个单独字符的纵横比与屏幕的纵横比匹配。