DEV Community

Cover image for Adding CSS to a Vue.js Project
Frida Nyvall
Frida Nyvall

Posted on • Updated on • Originally published at redonion.se

Adding CSS to a Vue.js Project

This is part of a series of articles starting with “Working with CSS in Vue.js”. Focus in this article is on different ways of adding CSS to a Vue.js project.

Separate Global Style Files

If you prefer to keep your style files separate from the .vue files and their style tags, similar to a workflow without a framework, this can be achieved. Setting up the style files this way means the styling will be applied to your template sections, but not available in component style tags.

Note: For example, if you create a SCSS variable in your style file, it will not be recognized if you try to use it within a component style tag. To get global styles available in component style tags, see the article about importing global styles in component style tags.

Set up your folder and file structure for your style files, for example src/styles/style.scss. If you use a structure with folders, _filename.scss and SCSS imports, this will work provided you have added SCSS support. (See the article “Working with CSS in Vue.js” on adding SCSS support.)

In your main.js file, import your styles below the Vue import:

import './styles/style.scss'

Style Tags in Vue Files

The default version of handling CSS is to write your styles in the vue file style tags.

Styles written in this way are global. Styles defined here are available in the project’s other .vue files.

<style>
  /*…write your styles here*/
</style>

Scoped Styletags

Scoping means adding data attributes to the different classes to keep them from leaking styles to one another. Scoping is similar to CSS Modules (read more about this in the article “CSS Modules in Vue.js”).

Add “scoped” to the component style tag in the .vue file:

<style scoped>
  /*add scoped styles here*/
</style>

Style Cascading

If a child component has a class name that is shared by its parent component, the parent component style will cascade to the child. Read more about nesting with the deep selector in the documentation.

To target children of scoped parents, use:

.parent >>> child { /*styles*/ }

Which syntax works depends on which preprocessor is used. Possible syntaxes are also:

.parent /deep/ child{ /*styles*/ }

.parent ::v-deep child{ /*styles*/ }

Read more about this in the vue-loader documentation.


Setup

The starting code for this article is created by the Vue CLI command tool version 3.3.0 and Vue.js version 2.6.10. Note that both setup, plugins and framework are evolving. Changes will in time most certainly happen that make the techniques described in this post less relevant.


Top comments (1)

Collapse
 
comnet profile image
ashish

I have created a simple project in Vue.
When I import css file Vue generates this type of style tag in the head section.
I don't want it.
Is there any other way to import CSS?

Image description