CSS coding tips
CSS 编码技巧
Minimize code duplication
尽量减少代码中的重复
Myth is an experimental preprocessor that emulates these native CSS features, instead of introducing proprietary syntax, essentially acting like a CSS polyfill
Myth 是一款实验性质的预处理器,它只去模拟上述这些原生的 CSS 新特性,而不是引入私有语法。它本质上扮演了 CSS polyfill 的角色。
Note that native features like these are generally much more powerful than the ones provided by preprocessors , as they are dynamic. For example, a preprocessor has no clue how to perform a calculation like 100% - 50px , because the value percentages resolve to is not known until the page is actually rendered. However, native CSS calc() has no trouble evaluating such expressions. Similarly, variable use like the following is not possible with preprocessor variables:
请注意这些原生特性通常会 比预处理器提供的版本要强大得多 ,因为它们是动态的。举个例子,预处理器完全不知道如何完成 100% - 50px 这样的计算,因为在页面真正被渲染之间,百分比值是无法解析的。但是,原生 CSS 的 calc() 在计算这样的表达式时没有任何压力。与此类似,下面这样的变量玩法在预处理器中是不可能做到的:
{原书注释!}
Don’t forget that native CSS features like these can be manipulated through scripting too. For example, you could use JS to change the value of a variable.
不要忘了这样的原生 CSS 特性也可以通过脚本来操纵。比如说,你可以用 JS 来改变一个变量的值。
ul { --accent-color: purple; }ol { --accent-color: rebeccapurple; }li { background: var(--accent-color); }
Can you see what we did there? The background of list items in ordered lists will be rebeccapurple , whereas the background of list items in unordered lists will be purple . Try doing that with a preprocessor! Of course, in this case, we could have just used descendant selectors, but the point of the example was to show how dynamic these variables will be.
你看清楚这段代码的意图了吗?有序列表的列表项的背景色将是 rebeccapurple ,但在无序列表中,列表项的背景色将是 purple 。你试试用预处理器能不能做到吧!当然,在这个例子中,我们可以直接使用后代选择符,只不过这个例子的重点在于——向你展示 CSS 的原生变量所具备的动态性。
Because most of the aforementioned native CSS features are not well supported today, in many cases using preprocessors is unavoidable if maintainability matters (and it should). My advice would be to start off every project with pure CSS, and when it starts being impossible to keep it DRY, switch to using a preprocessor then. To avoid becoming completely dependent on preprocessors or using them when they are not actually needed, their use needs to be a conscious decision , not a mindless first step performed by default in every new project.
上面提到的原生 CSS 特性绝大多数在目前还没有得到很好的支持,因此,在很多情况下,如果可维护性很重要(它确实很重要),使用预处理器是不可避免的。我的建议是,在每个项目开始时使用纯 CSS,只有当代码开始变得无法保持 DRY 时,才切换到预处理器的方案。为了避免可能发生的 “依赖” 或 “滥用”, 在引入预处理器的问题上需要冷静决策 ,不应该在每个项目一开始时就不动脑筋顺着惯性来。
In case you were wondering (and haven’t read the first chapter, tsk-tsk), the style of this book was authored in SCSS , although it started as pure CSS and only switched when the code grew too complex to be maintainable. Who said CSS and its preprocessors are only for the Web?
可能你还不知道(居然直接跳过前言了,啧啧),这里再说一次, 这本书的样式是用 SCSS 写的 。但这些样式代码是以纯 CSS 起步的,而且只在代码增长得太过复杂以致无法维护时才切到 SCSS 的。谁说 CSS 和预处理器只能用在网页上?
查看更多关于CSS编码技巧_html/css_WEB-ITnose的详细内容...