Sass-like functions in PostCSS

落爺英雄遲暮 提交于 2021-02-07 12:33:16

问题


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

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;
}

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


回答1:


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.

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

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.

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}%`
    }
  }
});

Which should allow you to write CSS like so:

input.css

.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.

Hope that helps!




回答2:


PostCSS doesn't allow you to write functions directly in CSS, however, with extra extension you are able to write functions in pure js, which will gives you almost unlimited possibilities.

Recently there was also created an extension https://github.com/titancat/postcss-define-function which enables you to implement basic arithmetics transformations +、-、*、/.

In your specific case, you can also use custom measuring units. In your example you could call it gw and gwpx (grid width pixels). That would enable you to use it this way:

.class{
  width:3gw;
}
.class2{
  width:3gwpx;
}

Which will be translated to

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


来源:https://stackoverflow.com/questions/37047910/sass-like-functions-in-postcss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!