Movatterモバイル変換


[0]ホーム

URL:


TryMCP servers to extend agent mode in VS Code!

Dismiss this update

CSS, SCSS and Less

Visual Studio Code has built-in support for editing style sheets in CSS.css, SCSS.scss and Less.less. In addition, you can install an extension for greater functionality.

Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in theMarketplace.

IntelliSense

VS Code has support for selectors, properties and values. Use⌃Space (Windows, LinuxCtrl+Space) to get a list of context specific options.

IntelliSense in CSS

Proposals contain extensive documentation, including a list of browsers that support the property. To see the full description text of the selected entry, use⌃Space (Windows, LinuxCtrl+Space).

Syntax coloring & color preview

As you type, there is syntax highlighting as well as in context preview of colors.

Syntax and color

Clicking on a color preview will launch the integrated color picker which supports configuration of hue, saturation and opacity.

Color picker in CSS

Tip: You can trigger between different color modes by clicking on the color string at the top of the picker.

You can hide VS Code's color previews by setting the followingsetting:

"editor.colorDecorators":false

To just disable it for css, Less and SCSS, use

"[css]": {    "editor.colorDecorators":false}

Folding

You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Folding regions are available for all declarations (for example, rule declarations) and for multiline comments in the source code.

Additionally you can use the following region markers to define a folding region:/*#region*/ and/*#endregion*/ in CSS/SCSS/Less or// #region and// #endregion In SCSS/Less.

If you prefer to switch to indentation based folding for CSS, Less and SCSS, use:

"[css]": {    "editor.foldingStrategy":"indentation"},

Emmet snippets

Emmet abbreviation support is built into VS Code, suggestions are listed along with other suggestions and snippets in the editor auto-completion list.

Tip: See the CSS section of theEmmet cheat sheet for valid abbreviations.

VS Code also supportsUser Defined Snippets.

Syntax Verification & Linting

There is support for CSS version <= 2.1, Sass version <= 3.2 and Less version <= 2.3.

Note: You can disable VS Code's default CSS, Sass or Less validation by setting the corresponding.validate User or Workspacesetting to false.

"css.validate":false

Go to Symbol in file

You can quickly navigate to the relevant CSS symbol in the current file by pressing⇧⌘O (Windows, LinuxCtrl+Shift+O).

Hovers

Hovering over a selector or property will provide an HTML snippet that is matched by the CSS rule.

Hover in CSS

Go to Declaration and Find References

This is supported for Sass and Less variables in the same file.CSS variables per thedraft standards proposal are also supported.

There is jump to definition for@import andurl() links in CSS, SCSS and Less.

CSS custom data

You can extend VS Code's CSS support through a declarativecustom data format. By settingcss.customData to a list of JSON files following the custom data format, you can enhance VS Code's understanding of new CSS properties, at-directives, pseudo-classes and pseudo-elements. VS Code will then offer language support such as completion & hover information for the provided properties, at-directives, pseudo-classes and pseudo-elements.

You can read more about using custom data in thevscode-custom-data repository.

Formatting

The CSS Languages Features extension also provides a formatter. The formatter works with CSS, LESS and SCSS. It is implemented by theJS Beautify library and comes with the following settings:

The same settings also exist forless andscss.

Transpiling Sass and Less into CSS

VS Code can integrate with Sass and Less transpilers through our integratedtask runner. We can use this to transpile.scss or.less files into.css files. Let's walk through transpiling a simple Sass/Less file.

Step 1: Install a Sass or Less transpiler

For this walkthrough, let's use either thesass orless Node.js module.

Note: If you don't haveNode.js and thenpm package manager already installed, you'll need to do so for this walkthrough.Install Node.js for your platform. The Node Package Manager (npm) is included in the Node.js distribution. You'll need to open a new terminal (command prompt) fornpm to be on your PATH.

npm install -g sass less

Step 2: Create a simple Sass or Less file

Open VS Code on an empty folder and create astyles.scss orstyles.less file. Place the following code in that file:

$padding:6px;nav {  ul {    margin:0;    padding:$padding;    list-style:none;  }  li {display:inline-block; }  a {    display:block;    padding:$padding 12px;    text-decoration:none;  }}

For the Less version of the above file, just change$padding to@padding.

Note: This is a very simple example, which is why the source code is almost identical between both file types. In more advanced scenarios, the syntaxes and constructs will be much different.

Step 3: Create tasks.json

The next step is to set up the task configuration. To do this, runTerminal >Configure Tasks and clickCreate tasks.json file from template. In the selection dialog that shows up, selectOthers.

This will create a sampletasks.json file in the workspace.vscode folder. The initial version of file has an example to run an arbitrary command. We will modify that configuration for transpiling Sass/Less instead:

// Sass configuration{  // See https://go.microsoft.com/fwlink/?LinkId=733558  // for the documentation about the tasks.json format  "version":"2.0.0",  "tasks": [    {      "label":"Sass Compile",      "type":"shell",      "command":"sass styles.scss styles.css",      "group":"build"    }  ]}
// Less configuration{  // See https://go.microsoft.com/fwlink/?LinkId=733558  // for the documentation about the tasks.json format  "version":"2.0.0",  "tasks": [    {      "label":"Less Compile",      "type":"shell",      "command":"lessc styles.less styles.css",      "group":"build"    }  ]}

Step 4: Run the Build Task

As this is the only command in the file, you can execute it by pressing⇧⌘B (Windows, LinuxCtrl+Shift+B) (Run Build Task). The sample Sass/Less file should not have any compile problems, so by running the task all that happens is a correspondingstyles.css file is created.

Since in more complex environments there can be more than one build task we prompt you to pick the task to execute after pressing⇧⌘B (Windows, LinuxCtrl+Shift+B) (Run Build Task). In addition, we allow you to scan the output for compile problems (errors and warnings). Depending on the compiler, select an appropriate entry in the list to scan the tool output for errors and warnings. If you don't want to scan the output, selectNever scan the build output from the presented list.

At this point, you should see an additional file show up in the file liststyles.css.

If you want to make the task the default build task to run executeConfigure Default Build Task from the globalTerminal menu and select the correspondingSass orLess task from the presented list.

Note: If your build fails or you see an error message such as "An output directory must be specified when compiling a directory", be sure the filenames in yourtasks.json match the filenames on disk. You can always test your build by runningsass styles.scss styles.css from the command line.

Automating Sass/Less compilation

Let's take things a little further and automate Sass/Less compilation with VS Code. We can do so with the same task runner integration as before, but with a few modifications.

Step 1: Install Gulp and some plug-ins

We will useGulp to create a task that will automate Sass/Less compilation. We will also use thegulp-sass plug-in to make things a little easier. The Less plug-in isgulp-less.

We need to install gulp both globally (-g switch) and locally:

npm install -g gulpnpm install gulp gulp-sass gulp-less

Note:gulp-sass andgulp-less are Gulp plug-ins for thesass andlessc modules we were using before. There are many other Gulp Sass and Less plug-ins you can use, as well as plug-ins for Grunt.

You can test that your gulp installation was successful by typinggulp -v in the terminal. You should see a version displayed for both the global (CLI) and local installations.

Step 2: Create a simple Gulp task

Open VS Code on the same folder from before (containsstyles.scss/styles.less andtasks.json under the.vscode folder), and creategulpfile.js at the root.

Place the following code in thegulpfile.js file:

// Sass configurationvar gulp =require('gulp');var sass =require('gulp-sass')(require('sass'));gulp.task('sass',function(cb) {  gulp    .src('*.scss')    .pipe(sass())    .pipe(      gulp.dest(function(f) {        return f.base;      })    );  cb();});gulp.task(  'default',  gulp.series('sass',function(cb) {    gulp.watch('*.scss',gulp.series('sass'));    cb();  }));
// Less configurationvar gulp =require('gulp');var less =require('gulp-less');gulp.task('less',function(cb) {  gulp    .src('*.less')    .pipe(less())    .pipe(      gulp.dest(function(f) {        return f.base;      })    );  cb();});gulp.task(  'default',  gulp.series('less',function(cb) {    gulp.watch('*.less',gulp.series('less'));    cb();  }));

What is happening here?

  1. Ourdefault gulp task first runs thesass orless task once when it starts up.
  2. It then watches for changes to any SCSS/Less file at the root of our workspace, for example the current folder open in VS Code.
  3. It takes the set of SCSS/Less files that have changed and runs them through our respective compiler, for examplegulp-sass,gulp-less.
  4. We now have a set of CSS files, each named respectively after their original SCSS/Less file. We then put these files in the same directory.

Step 3: Run the gulp default task

To complete the tasks integration with VS Code, we will need to modify the task configuration from before to run the default Gulp task we just created. You can either delete thetasks.json file or empty it only keeping the"version": "2.0.0" property. Now executeRun Task from the globalTerminal menu. Observe that you are presented with a picker listing the tasks defined in the gulp file. Selectgulp: default to start the task. We allow you to scan the output for compile problems. Depending on the compiler, select an appropriate entry in the list to scan the tool output for errors and warnings. If you don't want to scan the output, selectNever scan the build output from the presented list. At this point, if you create and/or modify Less or SASS files, you see the respective CSS files generated and/or changes reflected on save. You can also enableAuto Save to make things even more streamlined.

If you want to make thegulp: default task the default build task executed when pressing⇧⌘B (Windows, LinuxCtrl+Shift+B) runConfigure Default Build Task from the globalTerminal menu and selectgulp: default from the presented list.

Step 4: Terminate the gulp default Task

Thegulp: default task runs in the background and watches for file changes to Sass/Less files. If you want to stop the task, you can use theTerminate Task from the globalTerminal menu.

Customizing CSS, SCSS and Less Settings

You can configure the following lint warnings asUser and Workspace Settings.

Thevalidate setting allows you turn off the built-in validation. You would do this if you rather use a different linter.

IdDescriptionDefault
css.validateEnables or disables all css validationstrue
less.validateEnables or disables all less validationstrue
scss.validateEnables or disables all scss validationstrue

To configure an option for CSS, usecss.lint. as the prefix to the id; for SCSS and Less, usescss.lint. andless.lint..

Set a setting towarning orerror if you want to enable lint checking, useignore to disable it. Lint checks are performed as you type.

IdDescriptionDefault
validateEnables or disables all validationstrue
compatibleVendorPrefixesWhen using a property with a vendor-specific prefix (for example-webkit-transition), make sure to also include all other vendor-specific properties e.g.-moz-transition,-ms-transition and-o-transitionignore
vendorPrefixWhen using a property with a vendor-specific prefix for example-webkit-transition, make sure to also include the standard property if it exists e.g.transitionwarning
duplicatePropertiesWarn about duplicate properties in the same rulesetignore
emptyRulesWarn about empty rulesetswarning
importStatementWarn about using animport statement as import statements are loaded sequentially which has a negative impact on web page performanceignore
boxModelDo not usewidth orheight when usingpadding orborderignore
universalSelectorWarn when using the universal selector* as it is known to be slow and should be avoidedignore
zeroUnitsWarn when having zero with a unit e.g.0em as zero does not need a unit.ignore
fontFacePropertiesWarn when using@font-face rule without defining asrc andfont-family propertywarning
hexColorLengthWarn when using hex numbers that don't consist of three or six hex numberserror
argumentsInColorFunctionWarn when an invalid number of parameters in color functions e.g.rgberror
unknownPropertiesWarn when using an unknown propertywarning
ieHackWarn when using an IE hack*propertyName or_propertyNameignore
unknownVendorSpecificPropertiesWarn when using an unknown vendor-specific propertyignore
propertyIgnoredDueToDisplayWarn when using a property that is ignored due to the display. For example, withdisplay: inline, thewidth,height,margin-top,margin-bottom, andfloat properties have no effect.warning
importantWarn when using!important as it is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored.ignore
floatWarn when usingfloat as floats lead to fragile CSS that is easy to break if one aspect of the layout changes.ignore
idSelectorWarn when using selectors for an id#id as selectors should not contain IDs because these rules are too tightly coupled with the HTML.ignore

Next steps

Read on to find out about:

  • Configure Tasks - Dig into Tasks to help you transpile your SCSS and Less to CSS.
  • Basic Editing - Learn about the powerful VS Code editor.
  • Code Navigation - Move quickly through your source code.
  • HTML - CSS is just the start, HTML is also very well supported in VS Code.

Common questions

Does VS Code provide a color picker?

Yes, hover over a CSS color reference and the color picker is displayed.

Is there support for the indentation based Sass syntax (.sass)?

No, but there are several extensions in the Marketplace supporting the indented flavor of Sass, for example, theSass extension originally created by Robin Bentley, now maintained by Leonard Grosoli.

07/09/2025

[8]ページ先頭

©2009-2025 Movatter.jp