|
Post by account_disabled on Jan 28, 2024 1:37:07 GMT -5
这是 2015 年 3 月 5 日首次发表的文章的更新版本。 很久以前,在互联网过去的浓雾中,勇敢的冒险家以几乎相同的方式应对危险:使用固定的 960 像素布局,在设定的网格中战斗,并以像素为单位进行排版以抵御邪恶。 自那以后,响应式网页设计改变了这一切,让我们走出了迷雾,进入了启蒙时代。然而,在网络上使用排版有时仍然很痛苦。随着从像素或点到百分比和 ems 的推动,我发现自己在每个项目开始时甚至经常在整个项目中不断地需要谷歌“像素到百分比转换图表”或类似的东西。 沮丧中,我最终求助于Sass的力量,打造了一个新的、包罗万象的函数来解决这些问题,今天你将和我一起构建这个函数。 它将允许您在像素、em 和百分比值之间自由转换,而无需每次都查阅图表,并且希望能减轻您在此过程中的许多麻烦。 Learn to Code with JavaScript 在 Sass 中设置印刷单位转换 font-size首先,在 CSS 中定义默认值非常重要。 大多数浏览器将默认为16px,但如果您的项目需要不同的东西,请确保您的 CSS 知道它。此外,大多数样板都已16px定义为其默认值,因此我也将假定它为本教程的默认值。 然后您需要决定要支持哪些单位。由于这可能对打印到 Web 环境很有帮助,甚至只 WhatsApp 号码数据 是在 Photoshop 中启动并在浏览器中结束的项目,因此您将查看像素、点、em 和百分比。 您还想为自己提供在它们之间自由转换的选项,因此您可以说您的函数至少需要三个参数第一个参数是font-size您要转换的单位的数字(例如 16),第二个参数是您计划转换的单位(例如像素),第三个参数是您想要转换的单位(例如百分比)。因此,举个例子,如果您想将 16 像素转换为百分比值,您可以这样做:这会给你:让我们来吧 现在,是时候解决大括号之间的问题了。 首先,您希望能够处理像素、ems、点和百分比,因此您需要四个语句来处理所有这些。 如果您使用的是成熟的编程语言,则可以使用switch 语句。 由于这是 Sass,因此您将坚持使用if 语句 现在,您对每个可能的输入单位都有一个 if 语句(无论您想要以像素、em、点还是百分比开始)。所以这大约是 50% 的事情。您现在所要做的就是在这些 if 语句中添加一些很棒的东西! 加入 Sass 印刷单位转换的数学运算 好的,现在事情变得非常数学化了。假设您使用 16px 作为默认值font-size,您必须将其转换为 em 和百分比,如下所示 同样,每次转换使用一个 if 语句(一个用于 em,一个用于百分比),然后进行一些数学计算以获得所需的输出。我不会为点值做一个案例,因为无论如何它们只适用于打印 CSS。 对于 em(默认大小为 16 像素),您只需除以 16 并添加“em”单位的百分比有点棘手。你不能像使用 ems 一样在语句末尾抛出一个“%”,因为 Sass 会立即抛出一个错误(大意是“你在做什么把它放在那里!”)。所以这里需要结合Sass的百分比函数才能返回有效的百分比单位。
|
|