食谱
在本节中,我们将探讨如何充分利用 EffCSS 的功能。
一个键对应多个值
某些 CSS 属性在不同浏览器上的支持情况有所不同,因此您可能需要指定多个选项。为此,请使用数组并按所需顺序排列值:
ts
import { customStyles } from 'effcss';
customStyles(() => {
return {
'.cls': {
textDecoration: ['underline', 'underline dotted']
} // -> .cls{text-decoration:underline;text-decoration:underline dotted;}
};
});这同样适用于对象:
ts
import { customStyles } from 'effcss';
customStyles(() => {
return {
'@font-face': [
{
fontFamily: '"Bitstream Vera Serif Bold"',
src: 'url("https://mdn.github.io/shared-assets/fonts/FiraSans-Regular.woff2")'
},
{
fontFamily: '"MyHelvetica"',
src: 'local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url("MgOpenModernaBold.woff2")',
fontWeight: 'bold'
}
] // -> @font-face { /* Bitstream Vera Serif Bold */} @font-face { /* MyHelvetica */};
};
});通用字体名称
font 和 fonts 工具允许您指定一个通用字体名称,该名称将始终用作最后一个备用值:
ts
import { font, customStyles } from 'effcss';
const base = font({
src: `url("https://mdn.github.io/shared-assets/fonts/FiraSans-Regular.woff2")`,
genericName: 'sans-serif'
});
const alt = font({
src: `url("/fonts/roboto-regular.woff2") format("woff2"), url("/fonts/roboto-regular.woff") format("woff")`,
weight: 400,
style: 'normal',
display: 'swap'
});
customStyles(() => {
return {
body: {
fontFamily: base() // -> fontFamily: "base font name", sans-serif;
},
'.alt': {
fontFamily: alt('"Inter"') // -> fontFamily: "alt font name", "Inter";
},
'.base-with-fallbacks': {
fontFamily: base(alt, '"Inter"') // -> fontFamily: "base font name", "alt font name", "Inter", sans-serif;
}
}
})独立样式生成器
您可以单独创建一个生成器函数,并使用它来动态生成样式表:
ts
import type { Generator } from 'effcss';
import { attributes, classNames } from 'effcss';
type Card = {
w: 's' | 'm' | 'l';
blur: true;
card: {
variant: 1 | 2;
rounded: true;
}
}
const stylesGenerator: Generator<Card> = (selectors) => {
const {w, card, blur} = selectors;
return {
[w.s]: {
width: '12px'
},
[blur.true]: {
filter: 'blur(5px)'
},
[card]: {
background: 'white'
},
[card.variant[1]]: {
width: 'auto',
display: 'block',
padding: '12px',
'&:hover': {
cursor: 'pointer'
}
},
// and so on
}
};
export const createStylesheet = (type: 'attr' | 'cls') => {
if (type === 'attr') return attributes(stylesGenerator);
else return classNames(stylesGenerator);
};