PostCSS中类似Sass的函数 [英] Sass-like functions in PostCSS

查看:39
本文介绍了PostCSS中类似Sass的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试PostCss,并试图找到与Sass相似的功能.我坚持使用的一个功能是类似Sass的功能.

I'm trying out PostCss and trying to find comparable features to Sass. The one feature I'm stuck on is Sass-like functions.

这是我的函数是Sass:

Here's my function is Sass:

// Variables.scss
$columns: 12; // Grid columns
$max-width: 1200px; // Grid max width

// Function.scss
@function grid($cols,$to-px:false) {
  @if ($to-px == false) { @return ($cols / $columns) * 100% };
  @return round(($max-width / $columns) * $cols);
}

// style.scss
.class {
  width: grid(3);
}
.class2 {
  width: grid(3,true);
}

// outputs to:

// style.css
.class {
  width: 25%;
}
.class2 {
  width: 300px;
}

在PostCSS中,我可以编写这样的函数来返回单个CSS值吗?

In PostCSS can I write a function like this that returns a single CSS value?

推荐答案

我不知道现有的PostCSS插件,该插件可让您在CSS内使用 @function ,但其中一个可能已经存在. postcss-define-function 提供了一些可比的功能,因此也许看看.

I'm not aware of an existing PostCSS plugin that allows you to use @function within CSS, but one may be out there. postcss-define-function provides some comparable functionalily, so maybe give that a look.

如果您所需要的不存在,则可以使用PostCSS的 atRule编写一个类(可能还有其他一些类).

If what you need doesn't exist, it should be possible to write one, using, PostCSS's atRule class (and likely some others).

但是,编写这样的插件会非常复杂,并且与PostCSS鼓励您编写样式的方式是相反的.

However, writing a plugin like that would be pretty complicated, and is also sort of antithetical to how PostCSS encourages you to author your styles.

PostCSS的主要优点之一是,它使您可以使用JavaScript来操纵样式.与其尝试使用CSS编写函数,不如考虑使用JavaScript编写函数. postcss-functions 看起来就是这样做的,您可以公开用JavaScript编写的函数,以便在CSS中使用.您给出的示例可能如下所示:

One of the main benefits of PostCSS is that it lets you manipulate your styles with JavaScript; rather than trying to write functions in CSS, consider writing them in JavaScript. postcss-functions looks like it does just this, allowing you to expose functions—written in JavaScript—to be used within your CSS. Your given example could look something like this:

require('postcss-functions')({
  functions: {
    grid:(cols, totalCols, maxWidth, toPx = false) {
      return toPx
        ? `${Math.round(maxWidth / cols * totalCols)}px`
        : `${cols / totalCols * 100}%`
    }
  }
});

应该允许您这样编写CSS:

Which should allow you to write CSS like so:

.class {
  width: grid(3, 12, 1200);
}

.class2 {
  width: grid(3, 12, 1200, true);
}

output.css

.class {
  width: 25%;
}

.class2 {
  width: 300px;
}

如果这不能完全按照您的预期工作,则可以随时向项目发出请求请求,或编写自己的插件.

If that doesn't work exactly as you expect it to, you can always make a pull request to the project, or write your own plugin.

希望有帮助!

这篇关于PostCSS中类似Sass的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆