Utilizing consistent CSS styles across VueJS components

Currently tackling a VueJS 2 project and facing issues with scoped styling when cleaning up the code.

My setup involves 3 components that share similarities, prompting me to utilize mixins for consolidating the code into one file. Each component makes use of these mixins for both template and vuejs functionalities. If I need to tweak specific conditions for a particular component, I can easily override the code within it, which is functioning smoothly so far.

However, my aim now is to transfer the scoped style to the mixins as well. Currently, the style is enclosed in

<style lang="scss" scoped></style>
tag, working effectively within its respective component but necessitating duplication of styling codes across all 3 components.

I could opt to include these styles in the global CSS file, but restricting them to only one of the 3 components poses a challenge.

Is there a method to incorporate these styles and apply them to mixins?

What approach would be considered best practice for addressing this scenario?

Answer №1

Vue simplifies this process.

Resolution

To incorporate shared styles in a component, follow these steps:

MyComponent.js

<template>
</template>

<script>
</script>

<style lang="scss" scoped>
  @import '@/scss/shared-styles.scss';
  @import 'styles.scss'; // regular CSS for the component
</style>

Another Approach

You may also import the shared CSS files directly within the component's CSS file as shown below.

MyComponent.js

<template>
</template>

<script>
</script>

<style lang="scss" scoped>
  @import 'styles.scss';
</style>

styles.scss

@import '@/scss/shared-styles.scss'

// remaining component-specific CSS

Automatically Include Global Styles

If you want certain styles to be accessible in ALL your components, consider this method.

vue.config.js

module.exports = {
  ...
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "@/scss/global.scss";
        `
      },
    },
  },
}

Answer №2

I recently discovered that the scoped style also impacts child components.

As a result, I came up with a solution that may not be considered best practice, but it works well for me.

To implement this, I created a WrapperComponent where I placed the scoped style along with a simple template.

<template>
    <div>
        <slot></slot>
    </div>
</template>

<style lang="scss" scoped>
    /* CSS styles applied to all children */
</style>

The idea is that by wrapping any components with the WrapperComponent, the HTML content will be passed through the slot without alteration and the styles will automatically apply.

In my use of mixins, I imported the wrapper and wrapped the component template with the WrapperComponent. Here's an example:

import WrapperComponent from './WrapperComponent'

let MyMixins = {

    template: `<wrapper-component>
        <div>
            Insert your HTML code here
        </div>
    </wrapper-component>`,


    components: {
        WrapperComponent,
    },
};

By using this mixins or in a child component, the styles from WrapperComponent will automatically be applied, making it easy to maintain consistency across different groups of components sharing the same parent style.

Answer №3

Consider utilizing modules in place of creating a style section with a scoped attribute.

By doing so, your CSS will remain scoped and separate from your overall styling.

Answer №4

Successfully integrated my fadeTransition.css file into the /assets directory of my vue app, and imported it using this method:

<template>
  <transition name="fade">
    <div v-if="showContent">test</div>
  </transition>
</template>
<script>
  import '@/assets/fadeTransition.css';
  // component definition
</script>

Contents of fadeTransition.css:

/* fade menus in, not out */
.fade-enter-active {
  transition: opacity .5s;
}
.fade-enter {
  opacity: 0;
}

Efficient and straightforward. Also compatible with scss.

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is a better method for aligning an image in the middle of a floated container?

Is there a better way to center an image within a floated div without using an extra p tag? I currently have the image inside a p tag and center the p, but it annoys me having that extra tag. Any suggestions on how to center the image itself? Thanks! Below ...

Closing the space between navigation bar choices

I'm currently working on my website's navbar menu and struggling to eliminate the gap between each of the navbar links. It seems that the li attributes with the class dropdown are slightly wider than the rest of the links, causing this issue. I&a ...

There has been no change in Vue2 compatibility with Laravel 5.4

I'm currently experimenting with Vue within a Laravel project. However, I've encountered an issue where after modifying the example.vue file and adding it to the view, the changes are not reflected in the view. The code snippet below showcases th ...

Using the dot operator to load an image

Is it possible to using the dot operator to load an image? Let's talk about this as a sample image URL <img src={{GET_PROFILE_DATA.googleProfileData.fullName}} alt="profile" class="home-screen-profile-image"> Take note of the unusual looking ...

Arranging DIV elements into rows and columns within a table

After working all night to fix a problem, my goal is to create this timetable: https://i.sstatic.net/dAt1J.png Specifically, I'm struggling to find a solution for rows 5, 6, and 7 in the first column. The image is from a program that only runs in IE ...

The CSS class is mistakenly being applied to the entire page instead of just the specific div it was

Here is the HTML code I am working with: <!DOCTYPE html> <head> <title></title> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'portfolio/mystyle.css' %}" /> <link rel="styl ...

Arrange a cluster of CSS table cells onto a fresh line

Currently, I am exploring CSS properties to create the visual appearance of a table using two levels of DOM elements. The highest-level element wraps around its child elements, which are styled to resemble a flat list. For example: <div class="t"> ...

Issue arises when combining inline-block and overflow-wrap for div elements

I am facing an issue with two divs that look good on the same line when utilizing display: inline-block. However, if one of the containers contains an excessively long word that I attempt to wrap using overflow-wrap and word-break, it causes the container ...

The function .classList.remove() is effective when applied to one element, but fails to work on a different element

I am facing an issue where only one element is getting affected when trying to remove classes from multiple elements if certain email input requirements are met. Can someone help me understand why this is happening? Here is the code snippet: const emailI ...

How can the caption be aligned to the right of the image within a Bootstrap thumbnail in a precise manner, while also ensuring the button is positioned at the bottom of the caption?

Greetings! I am in the process of developing a website using bootstrap v3.3.2. My first query revolves around utilizing the grid system to correctly position the caption on the right side of the thumbnail, as illustrated below: <div class="container"& ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

Position the center button evenly between two images, aligned vertically using percentages

I'm attempting to achieve a specific layout that includes images scaling across Bootstrap breakpoints and a static button position. The challenge is maintaining the layout as depicted in the mockup, regardless of image size. The images are set to im ...

Incorporate a video within the royal slider feature

Next is my deluxe slider code. This slider displays only images but I am looking to incorporate video as well. I have searched online and tried different solutions, but haven't found one that works for me. Can someone please guide me on how to achieve ...

Creating customizable divider lines with text next to them using HTML in emails

How can I create an adjustable line with a word next to it, ensuring that long words do not wrap onto a second line? I want the line to stay on one line and the left side to shrink accordingly. Also, I need the text input area to be flexible so I can input ...

Stacking two divs for the team section layout

Although I'm new to this, I've been struggling to achieve a specific layout for a team page. My goal is to display a picture on the left side and text on the right for each team member. The design includes the person's name, title, and a set ...

Center an element on the screen by dynamically adjusting its position according to the media query

As I work on creating a responsive website that can adapt to screens of various devices, I am facing a challenge. Each device has a different number of pixels, making it difficult to centrally position a div dynamically. Currently, I am using margin-left: ...

Vue Toggle Button: An error occurred while trying to perform the 'insertBefore' function on a 'Node' element

Using the Vue toggle button, I created functionality to hide or show columns in a table. Let's say there are 5 buttons in my child Vue component and I clicked on some of them to hide: Button 1 - Clicked to hide Button 2 Button 3 - Clicked to hide Butt ...

Which specific CSS rule is responsible for the issue I am currently experiencing?

I have styled a left-hand border on items in a list, with the border-left-color set to transparent for all of them. The active item, marked by the css class "active day", has a specific color for its border. Below is a snippet of the code (certain styles h ...

Setting initial opacity for CSS on page load

I'm not a pro at web design, but I'm trying to create my own website. I've divided my page into two sections - the left side for the menu bar and the right side for content. To add a 'cool' blur effect over my menu bar, I decided t ...

Is there a way to set the content to be hidden by default in Jquery?

Can anyone advise on how to modify the provided code snippet, sourced from (http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_show), so that the element remains hidden by default? <!DOCTYPE html> <html> <head> <scrip ...