Nesting SCSS Rules in VueJS Modules - css

How can I handle nested SCSS rules, which expand on a base style, when dealing with the CSS Modules to import styles to the local component?
In my case, I have the following two SCSS files:
icon.scss
.my-icon {
// base styles for an icon
}
button.scss
.my-button {
...
.my-icon {
// special styles when an icon is in a button
}
}
Which I then import into their respective components:
MyIcon.vue
<template><i class="my-icon" /></template>
<style lang="scss" module>
#import '/path/to/icon.scss'
</style>
MyButton.vue
<template><button class="my-button"><slot /></button></template>
<style lang="scss" module>
#import '/path/to/button.scss'
</style>
The trouble is that the nested .my-icon class, in 'button.scss', generates a different hash ('._2XJ5') than the root .my-icon class, in 'icon.scss' (._2UFd). So, when I attempt to embed an icon into a button I get an output that looks like this:
<button class="._3S2w"><i class="._2UFd" /></button>
Which is correct, but the "special styles" for an icon in a button are not applied, because that class was generated as a different hash.
How do I make sure the hash value for '.my-icon' always comes out the same?

Somewhere, hidden deep in the Vue loader, the documentation talks briefly about how you can escape the scoped styling. The solution is to use a /deep/ selector, which is preprocessed by scss to give everything behind it no hash. There is something similar in normal css, but it is somewhat unrelated.
Say we have our my-button component and want to style my-icon classes inside it, we can do the following:
<template>
<div>
<slot></slot>
</div>
</template>
<style lang="scss" scoped>
/deep/ .my-icon {
background: red;
}
</style>
The following should generate something like the following. It is still scoped within your component, but .my-icon does not have to be part of your component. In this case, it could be inside the slot for example.
[data-v-f3f3eg9] .my-icon {
background: red;
}

Related

how to call Sass variable in a Vue file

There is a variables.scss file in a project which defines a variable and assigns it a color like this:$contrast: #edebe4The current use of the $contrast variable is to set other variables within the variables.scss file.
Now there is a specific .vue file that's used to render data to the browser and it contains this line of code in its template:<div style="background-color: #edebe4">
When I change that line to<div style="background-color: $contrast">the desired background color disappears from that element.
Is there a way to get that element to recognize the $contrast variable so that whenever the value of $contrast is changed that change flows through automatically to this element?
You can make scss variables available globally (in each component). Just add this to vue.config.js:
css: {
loaderOptions: {
scss: {
additionalData: `#import "~#/variables.scss";`
}
}
}
More info here
Just import variables.scss into your .vue
...
<style lang="scss">
#import "variables.scss"
</style>
This worked -
in variables.scss file added
.contrast-background {
background-color: $contrast;
}
in .vue file changed element to this
<div class="contrast-background">
Amendment -
Here is the final solution that was implemented, which was made possible by #Finn's post -
Changes to .vue file:
added this
<style lang="scss" scoped>
#import "#/layout/design/variables.scss";
.contrast-background {
background-color: $contrast;
}
</style>
and changed element to this
<div class="contrast-background">
This approach avoids changes to the variables.scss file.

Vue3 - How to override styles after importing node_modules css file?

I have a standard Vue3 app using the library https://github.com/ismail9k/vue3-carousel.
In my App.vue file, I have the following, which is required to use the library:
<style>
#import "~vue3-carousel/dist/carousel.css";
</style>
Since I don't want to use the library's default colors, I'm trying to override some styles.
The library defines some colors on :root, such as:
--vc-clr-primary: #333333;
--vc-pgn-background-color: var(--vc-clr-primary);
Then, the style that I want to ultimately override is:
.carousel__pagination-button {
...
background-color: var(--vc-pgn-background-color);
}
So, I assume that I want to override either of the variables, or the class itself. In my Component.vue file, I have the following:
<style scoped>
.carousel__pagination-button {
background-color: #999999 !important;
}
</style>
But that doesn't do anything.
I don't care where I override these colors, because I'll use the same colors throughout the website, but I can't figure out how to get them to override no matter where or how I attempt to override them.
What am I doing wrong?
This worked:
App.vue
...
<style>
#app {
--vc-pgn-background-color: #mycolor;
}
#import "~vue3-carousel/dist/carousel.css";
</style>

Prefix css selectors for make styles from API safe

Let's assume that the user can add styles for every component in admin panel and I get it as string in my Node server:
const stylesFromAPI = ".p { color: red } .bg { background: lime }";
How to prefix this styles before append to my document to avoid conflicts?
I need something like CSS modules but working with strings (not as module loader):
const stylesFromAPI = css(".p { color: red } .bg { background: lime }"); // returns hashedClassname685946898456
<SomeCompontent className={stylesFromAPI} />
produces:
<style>
.hashedClassname685946898456 .p { color: red }
.hashedClassname685946898456 .bg { background: lime }
</style>
<div class="hashedClassname685946898456"></div>
Shadow DOM seems like a reasonable option here. You can create your style tags with inside the shadow DOM without having to deal with any selector prefixes. For example, using the react-shadow package:
import root from 'react-shadow';
Then in JSX, something like:
<root.div>
<style type="text/css">
{/* CSS string here */}
</style>
<div>
{/* Stuff here */}
</div>
</root.div>
Check out a working example of this here: https://github.com/joshdavenport/stack-overflow-61566764-react-css-shadow-dom
The main downside here is your styles from outside the shadow DOM will not apply. Those using the shadow DOM for components see this as a good thing, those simply trying to scope CSS do not. Not sure what it is you're scoping, so I can't really tell if that would be an issue for you.
If it is, you could re-import your styles within the shadow DOM, though I can't really point out how to do that without knowing what bundler is in use and how it is in use.
Alternatively you could pull apart your imported CSS using the css package, iterate over the selectors prefixing all with a randomly generated class, and then re-stringify.

How to load different .css files on different components of a react application?

I have two .jsx files that represent their respective components.
The first one is, Blog.jsx
import React from "react";
import '../assets/css/blog.css';
export const Blog = () => (
<div>
<h1>Hello Blog</h1>
</div>
)
With its respective CSS file, blog.css
div { background: #ff481f; }
and the second one is, Landing.jsx
import React from "react";
import '../assets/css/landing.css'
export const Landing = () => (
<div>
<h1>Hello Landing</h1>
</div>
)
With its respective CSS file, landing.css
div { background: #86ff2b; }
I have added routing and called instances of those two components on the App.js file which is the default file of a React application. After running the application, when navigated to components, I faced a problem that the background color is the same for both of the components (It loads landing.css only and never changes).
How can I fix that problem that each component only uses its respective .css file and loads it?
By default webpack and other build tools will compile all CSS files into one, even if css was imported in separate JSX files. So you can't use different CSS files and expect you don't affect on another part of page.
You have some options:
Use BEM for naming class names.
Use cssModules. In this case elements will have their own css class name and styles will not affect any other elements except if you use :global selector.
css-module
Using html tags as css selectors is a bad practice (because there is the behaviour you describe).
You should use only css classes or inline styles (using id's is another bad practise, id's have high priority).
div {
width: 20px;
height: 20px;
}
#id {
background: red;
}
.class {
background: green;
}
<div id="id" class="class"></div>
In case using css classes there is the same problem (when you have two similar classes). And this case is decided using css modules (set of rules of building) or you can use css-in-js (external library) which has its pros and cons. Also you can use BEM (methodology) and if your application is not big you can avoid this trouble.
css modules will add to your classes random hash and instead .my-awesome-class-name you will get .my-awesome-class-name-dew3sadf32s.
So, if you have two classes .class in the first file and .class in the second file in the end you will get two classes .class-dew23s2 and .class-dg22sf and you styles will resolve as expected.
css-in-js is a similar way except you should write your styles using javascript with some profits like including only those styles that are needed at the moment (what you are looking for right now) and several others.
You can code using pure css / scss / postcss / etc but many companies already choose between css modules and css-in-js.
BEM is just naming conventions for your class names.
And lastly - if you use inline-styles using react you should remember:
{} is constructor of object and {} returns new object on every call, it's mean if you write something like:
class MyAwesomeComponent extends Component {
render() {
return <div style={{color: "red"}}></div>;
}
}
or
class MyAwesomeComponent extends Component {
render() {
const divStyles = {color: "red"};
return <div style={divStyles}></div>;
}
}
div will re-render every time your render will call because div takes new prop.
Instead, you should define your styles (for example) in outside of your class:
const divStyles = {color: "red"};
class MyAwesomeComponent extends Component {
render() {
return <div style={divStyles}></div>;
}
}
Don't define your css using HTML tags because it will affect your entire application.
use className,id or inline styling.
like- App.css
.myApp{ color: red;}
#myApp2{ color: blue;}
App.js
import './App.css'
<div className="myApp">color changed by className</div>
<div id="myApp2">color changed by id</div>
<div style={{color:'red'}}>color changed by inline object styling</div> // inline styling
This is not the best solution if you are looking forward to improve yours css imports/loads.
However could be the best solution if you dont want to go in deep in css, resolve the problem fast and keep working with HTML tag.
You can add a div for each component, define an Id for the div and wrap the component. Afterwards in the component's css fies you are going to define all the styles starting with the #id so all the css classe or HTML tag will affect just the corresponding component.
//App render in root
ReactDOM.render(
<App />,
document.getElementById('root')
);
//App
function App(props){
return [
<Blog />, <OtherComponent />
]
}
//Blog component
function Blog(props){
return <div id="blog">
<h1>I am Blog</h1>
</div>
}
//Other component
function OtherComponent(props){
return <div id="otherComponent">
<h1>Im am other component</h1>
</div>
}
/* blog.css*/
#blog h1{
color:yellow;
}
/* otherComponent.css*/
#otherComponent h1{
color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

How to override scoped styles in Vue components?

Let's save I have a .Vue component that I grab off of Github somewhere. Let's call it CompB and we'll add a single CSS rule-set there for a blue header:
CompB.Vue (a dependency I don't own, perhaps pulled from Github)
<template>
...
</template>
<script>
...
</script>
<style lang="scss" scoped>
.compb-header {
color: blue;
}
</style>
I plan to nest CompB into my own project's CompA. Now what are my options for overriding the scoped rule?
After playing around a bit, I think I've got a good approach.
Global overrides
For situations where I want to override the rules in all cases for CompB I can add a rule-set with more specificity like this: #app .compb-header { .. }. Since we always only have one root (#app) it's safe to use an ID in the rule-set. This easily overrides the scoped rules in CompB.
Parent overrides
For situations where I want to override both the global and scoped rules. Thankfully VueJS allows adding both a scoped and unscoped style block into a .Vue file. So I can add an even more specific CSS rule-set. Also notice I can pass a class into CompB's props since Vue provides built-in class and style props for all components:
// in CompA (the parent)
<template>
...
<!-- Vue provides built-in class and style props for all comps -->
<compb class="compb"></compb>
</template>
<script>
...
</script>
<style lang="scss">
#app .compb .compb-header {
color: red;
}
</style>
<style lang="scss" scoped>
...
</style>
(note: You can get more specific and make the class you pass into CompB have a more unique name such as .compa-compb or some hash suffix so there is no potential for collision with other components that use CompB and a class .compb. But I think that might be overkill for most applications.)
And of course CompB may provide its own additional props for adjusting CSS or passing classes/styles into areas of the component. But this may not always be the case when you use a component you don't own (unless you fork it). Plus, even with this provided, there is always those situations where you are like "I just want to adjust that padding just a bit!". The above two solutions seem to work great for this.
You will need to add more specificity weight to your css. You have to wrap that component in another class so you can override it. Here is the complete code
<template>
<div class="wrapper">
<comp-b>...</comp-b>
</div>
</template>
<script>
import CompB from 'xxx/CompB'
export default {
components: {
CompB
}
}
</script>
<style>
.wrapper .compb-header {
color: red;
}
</style>

Resources