我正在尝试使用PostCss并试图找到与Sass相似的功能.我坚持的一个功能是类似Sass的功能.
这是我的功能是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;
}
Run Code Online (Sandbox Code Playgroud)
在PostCSS中,我可以编写一个返回单个CSS值的函数吗?
我不知道现有的 PostCSS 插件允许您@function在 CSS 中使用,但可能有一个。postcss-define-function提供了一些可比较的功能,所以也许看看。
如果您需要的东西不存在,那么应该可以使用 PostCSS 的atRule类(可能还有其他一些类)编写一个。
然而,编写这样的插件会非常复杂,而且与 PostCSS 鼓励您创作样式的方式有点背道而驰。
PostCSS 的主要好处之一是它允许您使用 JavaScript 来操作您的样式;与其尝试用 CSS 编写函数,不如考虑用 JavaScript 编写它们。postcss-functions看起来它就是这样做的,允许您公开用 JavaScript 编写的函数以在您的 CSS 中使用。您给定的示例可能如下所示:
require('postcss-functions')({
functions: {
grid:(cols, totalCols, maxWidth, toPx = false) {
return toPx
? `${Math.round(maxWidth / cols * totalCols)}px`
: `${cols / totalCols * 100}%`
}
}
});
Run Code Online (Sandbox Code Playgroud)
这应该允许您像这样编写 CSS:
.class {
width: grid(3, 12, 1200);
}
.class2 {
width: grid(3, 12, 1200, true);
}
Run Code Online (Sandbox Code Playgroud)
.class {
width: 25%;
}
.class2 {
width: 300px;
}
Run Code Online (Sandbox Code Playgroud)
如果这与您期望的不完全一样,您可以随时向项目发出拉取请求,或编写自己的插件。
希望有帮助!
PostCSS 不允许您直接在 CSS 中编写函数,但是,通过额外的扩展,您可以在纯 js 中编写函数,这将为您提供几乎无限的可能性。
\n\n最近还创建了一个扩展https://github.com/titancat/postcss-define-function,它使您能够实现基本的算术转换+\xe3\x80\x81-\xe3\x80\x81*\xe3\x80\x81/。
根据您的具体情况,您还可以使用自定义测量单位。在您的示例中,您可以将其称为gw“and” gwpx(网格宽度像素)。这将使您能够以这种方式使用它:
.class{\n width:3gw;\n}\n.class2{\n width:3gwpx;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这将被翻译成
\n\n.class{\n width:25%;\n}\n.class2{\n width:300px;\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2238 次 |
| 最近记录: |