search
HomeWeb Front-endHTML TutorialSass 与 Compass 实战经验总结_html/css_WEB-ITnose

自从走进前端圈,一直忙于学习和工作,虽有经常记下点滴收获,却没有时间好好地写出来。此刻,恰逢"五一",正好挤时间写写博客,跟大家分享下近期结合使用Sass和Compass的一些经验。文章主要面向对Sass和Compass还不太熟悉的同学,相信对你有一定的帮助。大牛请补充,欢迎留下建议或补充说明。

Sass 和 Compass 的安装

Sass和Compass的安装大家可以参考它们各自的官网,里面有详细的install步骤。以下是它们的官网:

  • Sass官网

  • Compass官网

这里需要提下,安装Sass和Compass之前,请先确保本地已经装了Ruby环境,因为这两者都是用Ruby语言开发的。至于Ruby环境的安装,本文提供两个途径:

  • 一个是 taobao镜像 ,

  • 一个是Ruby China上的 安装教程 。

Sass 的常用方法

Sass有两种语法规则 -- Sass 和 Scss, 以下所说的都是针对Scss语法。以下示例只给出Scss的写法,如有需要了解编译后样式的,推荐参考官网。

编译

Scss有四种编译风格,分别是:

  • nested(默认): 嵌套缩进

  • expanded: 扩展的

  • compact: 简洁格式

  • compressed: 压缩

至于怎么编译,我们放在下面跟Compass一起讲,因为这里主要分享和compass结合使用。如果要单独编译Sass,可以参考官网上提供的在线编辑器,或者用koala软件,一款Less、Sass编译器,如果项目中有用Gulp或Webpack,可以用它们的插件自行编译即可。

注释

以下两种注释方式,大家自取所需即可。

//这种注释方式,不会被编译到css文件中,只能保留在源文件/* 这种注释可以被编译到css文件中 */

变量

Scss语法支持使用变量,变量都以$符号开头,以下给出简单示例:

    $font-color: #ff637c;    $sm-padding: 6px;    .main {        color: $font-color;        padding-top: $sm-padding;    }

嵌套

Scss支持选择器嵌套使用,省去我们写很多相同的选择器名称,如:

    .prev-item {        border: 1px solid $primary-color;        padding: $sm-padding;        p {            line-height: 28px;        }    }

这里提醒一点,嵌套层级太深会影响网页性能,一般推荐嵌套不超过3层。

复用

scss代码的复用,这里讲以下几种:

1. @mixin 和 @include

    @mixin size($width, $height: $width) {        width: $width;        height: $height;    }    .containter {       @include size(60px);    }

2. class / placeholder 和 @extend

请大家看看以下两种形式,注意两种形式的编译结果:
    %auto {        margin-left: auto;        margin-right: auto;    }        .box {        @extend %auto;        width: 80px;    }
    .auto {        margin-left: auto;        margin-right: auto;    }        .content {        @extend .auto;        width: 80px;    }

第一种写法是Scss的placeholder的用法,编译结果如下,也就是”%auto“的样式是不会单独被编译出来的,只在引用它的选择器里面生效:

    .box {        margin-left: auto;        margin-right: auto;        width: 80px;    }

而第二个编译结果是

    .auto {        margin-left: auto;        margin-right: auto;    }        .content {          margin-left: auto;          margin-right: auto;         width: 80px;    }

因此,如果你的html中需要用到诸如”auto“这个类的,选用第二种方法,如果html中不需要用到“auto”这个类,scss中的“auto"纯属用来服务其他类的,那我们选择第一种方法,减少css中多余的样式。

3. @import

@import命令在css模块化的运用中起着重要的作用,它用来引入外部的文件。比如我们已经写好了_reset.scss、header.scss和modal.scss,如下:

这里我们在写index.scss时,需要用到header和modal的样式,那么我们直接在index.scss里面,通过@import命令引进来就行,如图:

这里提醒注意两点

  • scss文件的文件名如果是有下划线“—”,则不会单独被编译成一份css文件,而只会在引用它的文件里面编译。但是在引用它时,不用加上下划线, 如上面的 @import 'reset' ;

  • 确保每份scss文件最上面都有 @charset 'utf-8' , 以防编译中文注释时,出现乱码。

Sass还有很多高级用法,如自定义函数、条件语句等, 有兴趣的同学可以看看官方文档。

Compass 与 Sass结合使用

Compass和Sass结合使用,可以大大加快我们编写css的速度,因为Compass里面已经有很多现成的sass模板,我们可以直接拿来用。先看看在项目里面装了Compass以后,compass里面会有一个config.rb文件、一个存放Sass文件的文件夹和一个存放编译后的css文件夹(文件夹名称可自行修改),你也可以放入其他文件,如下图的images文件夹。

我们看看下图config.rb文件:

在代码的6~9行,我们可以设置文件的路径,在14行设置编译后的css格式,20行设置 line_comments = false 去除默认状态下大量的注释,如果需要去除缓存文件,则加上一句 cache = false 即可。

编译

如果项目中没有使用gulp或者webpack,单纯用compass来编译的话,可以命令行中项目的根目录下,执行 compass compile ,这样compass就会把Scss文件夹中的scss文件, 编译成css 并存放在css(或默认名为stylesheets)的文件夹里面。Compass 也可以像gulp或者webpack一样,实时编译,只需要在项目的根目录下,打 compass watch , 这样compass就会实时监听scss文件,一旦sass文件有改动,及立即编译到css文件。

模块引用

有了compass,我们不用再自己写一个reset.scss文件,或者定义一大堆css3的@mixin等,可以直接在scss文件里面引用compass的现成模块。具体模块很多,有兴趣的同学可以浏览官网,上面有详细的用法说明,这里只给出简单示例:

这样这份scss文件在编译后,就会自动生成 css reset 的代码,我们也可以通过 @include 来直接引用compass/css3中的19种命令,如 clearfix 、 box-sizing 或者其他css3新属性 border-radius 等,参考下图:

函数

Compass有很多封装好的函数,方便我们直接使用,这里挑个比较常用的讲下. 比如,我们在写背景图片路径时,可以引用 image-url 函数,直接在config.rb文件里面,配置好图片的路径,然后在scss文件中,直接把图片名称作为参数传给 image-url 即可,如图:

你也可以拿它再和scss结合使用,封装出更实用的代码,如封装一个兼容1倍屏和2倍屏图片的@mixin.

更多实例,请参考 这里 .

篇幅有限,就先写这么多了,如果你有更多的发现,欢迎一起分享...

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)