css – sass是否损害性能?

前端之家收集整理的这篇文章主要介绍了css – sass是否损害性能?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在教育自己阅读 this

The engine evaluates each rule from right to left,starting from the rightmost selector (called the “key”) and moving through each selector until it finds a match or discards the rule. (The “selector” is the document element to which the rule should apply.)

例如:

  1. ul li a {...}
  2. #footer h3 {...}
  3. * html #atticPromo ul li a {...]

现在,我的一些示例代码SASS输出

  1. #content #blog {
  2. /* ... */
  3. }
  4. /* line 85,../sass/screen.scss */
  5. #content #flickr {
  6. /* ... */
  7. }
  8.  
  9. #content #flickr div p {
  10. /* ... */
  11. }

这似乎有点尴尬..我做错了什么?这是我和Sass之间的沟通问题吗?我们失去了吗?

编辑:
一些SCSS代码

  1. #flickr {
  2. @include columns(5,8);
  3. background: url('../img/ipadbg.png') no-repeat;
  4.  
  5. #ipod-gloss {
  6. z-index: 999;
  7. position: relative;
  8. }
  9.  
  10. div {
  11. margin-top: -80px;
  12. margin-right: 20px;
  13.  
  14. h2 {
  15. color: $white;
  16. font-size: 24px;
  17. }
  18.  
  19. p {
  20. margin-top: 40px;
  21. }
  22. }
  23. }

Side Bonus!:文章说浏览器(或至少Firefox)从右到左搜索选择器.我不明白为什么这是一个更有效率的原因.任何线索?

解决方法

您必须在可维护性(嵌套使得在样式表中找到方法更容易)和渲染性能之间找到妥协.

经验法则说您应该尝试限制自己进行三级嵌套,如果没有必要,您应该避免嵌套ID.

但是,我认为嵌套太多并不是最大的问题.一旦我意识到mixins的力量,我就用了很多.

例如,这是我经常使用的按钮mixin:

  1. @mixin small-button($active-color: $active-color,$hover-color: $button-hover-color,$shadow: true)
  2. display: inline-block
  3. padding: 4px 10px
  4. margin:
  5. right: 10px
  6. bottom: 10px
  7. border: none
  8. background-color: $button-color
  9. color: $font-color-inv
  10. +sans-serif-font(9px,700)
  11. text-align: center
  12. text-transform: uppercase
  13. cursor: pointer
  14. @if $shadow
  15. +light-shadow
  16. &:hover
  17. text-decoration: none
  18. background-color: $hover-color
  19. &:last-child
  20. margin-right: 0
  21. a
  22. color: $font-color-inv
  23. &,&:hover
  24. text-decoration: none
  25. &.disabled
  26. +opacity(0.75)
  27. &:hover
  28. background-color: $button-color
  29. &.active
  30. background-color: $active-color
  31. &.disabled:hover
  32. background-color: $active-color

你看,相当多的代码.将这样的混合应用到页面上的许多元素将导致大的CSS文件需要更长的时间来解释.

在老式的CSS方式中,您可以给每个按钮元素类.小按钮.但是这种方法会使用非语义类来污染你的标记.

Sass提供了一个解决方案:选择器通过@extend directive继承.

如果您为mixin的参数设置默认值,您还可以提供一个简单的类,它使用默认的mixins:

  1. // Use this mixin via @extend if you are fine with the parameter defaults
  2. .small-button
  3. +small-button

然后,您可以在各种上下文中继承此类:

  1. #admin-interface
  2. input[type=submit]
  3. @extend .small-button

生成的CSS语句将.small按钮的所有用法聚合成一个带有逗号分隔选择符的规则:

  1. .small-button,#admin-interface input[type=submit] {
  2. display: inline-block;
  3. ...
  4. }

总而言之,Sass的天真使用可以影响您的CSS性能.但是,明智地使用它是可维护的,由于结构良好和DRY代码,它导致标记和样式(仅限语义类)的适当分离,并允许智能和执行CSS代码.

猜你在找的CSS相关文章