What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files:

/* styles/1.scss */
body {
  /* Some other styles not related to background-color */
}
/* styles/2.scss */
body {
  background-color: blue;
}
// pages/one.js
import "../styles/1.scss";

export default ()=>(
  <div>Hello, One!</div>
)

Upon visiting localhost:3000/one, I noticed that the background turns blue even though no style for background-color is defined in 1.scss!

I suspect this issue might be related to css modules, so I attempted wrapping 2.scss with :local. I also tried renaming 2.scss to 2.module.scss, but it did not fix the problem.

Any suggestions on how to resolve this? I appreciate your assistance!

Edit: You can view this issue on codesandbox: https://codesandbox.io/s/priceless-flower-oswh1

If the background color is not orange, try clicking "Go to two" and then return to one. The orange background will persist.

Answer №1

When styling the body element or providing css resets, global styles are necessary.

Method 1:

// one.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

and

// two.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: orange;
      }
    `}</style>

    Hello, Two!
    <Link href="/one">
      <a>Go to one</a>
    </Link>
  </div>
);

You can alternatively store the style in a separate file and import it as needed.

Method 2:

// styles/one_style.js
import css from "styled-jsx/css";

export default css.global`
  body {
    background-color: red;
  }
`;

and

// one.js
import globalStyles from "../styles/one_style";
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>
      {globalStyles}
    </style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

Code Sandbox

I trust this information will be beneficial to you.

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

Incorporating ScrollMagic and GSAP into Next.js: A Step-by-Step

A project built with Next.js includes the following component: import React, { PureComponent } from "react"; import { Power3, TimelineMax } from "gsap"; import ScrollMagic from "scrollmagic"; export default class TextFade extends PureComp ...

Exploring Ways to Access Console.log() from Client Pages in Next.js

Struggling to debug my client-side renderings using `Console.log()` (Any tips on an easier way to use the debug tool would be appreciated), as I can only access server-rendered console logs. I'm attempting to track the flow of information for this ha ...

Getting access to scope variables in an Angular controller written in ES6 style can be achieved by using

In my new Angular project, I decided to switch to using ES6 (Babel). However, I encountered an issue where ES6 classes cannot have variables. This led me to wonder how I could set my $scope variable now. Let's consider a simple controller: class Mai ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Steps to execute a JSON file once another JSON has been successfully loaded

I'm facing a similar challenge to the one presented in this question. However, I need to load an additional JSON file after the when() method is executed. Essentially, I want to retrieve JSON data within the when() function and then use that informati ...

When you use jQuery's serialize() method on a form element, it will only serialize one form element at a time

Consider the form below: <form id="form" name="form"> <input name="name"/> <input name="version"/> <input name="template"/> <textarea name="elements"></textarea> <textarea name="features"></textarea> <tex ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

Using VueJS to showcase user input in a dynamic list and a pop-up modal

I am attempting to achieve the following: Use a v-for loop to display form input (name, position, company) as an unordered list, showing only the name input and a button for each person When a button is clicked, a modal will appear displaying all the data ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

Streamline the process of renaming or remapping keys in a collection of JavaScript/JSON objects

Structured JSON data is essential. Imagine using JSON.parse(): [ { "title": "pineapple", "uid": "ab982d34c98f" }, { "title": "carrots", "uid": "6f12e6ba45ec" } ] The goal is to transform it by changing titl ...

Incorporate a background only if the specified condition in AngularJS is met, utilizing ng-style

I'm struggling to incorporate a background url style based on a given condition. I tried using data-ng-style, but for some unknown reason, it's not working as expected. I'm not sure where I'm going wrong. data-ng-style="true : {'b ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

What is the best way to use jQuery to listen for a container resizing event?

I am confident that I can achieve this: $(window).resize(function() {funkyfunc();}); The above code will execute funkyfunc() whenever the window is resized. However, my issue lies in wanting to resize one control after another has been resized. I've ...

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants: My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on th ...

What is the best way to access the properties of individual objects within an array of objects in a MongoDB MapReduce JavaScript query?

Need help referencing each property of an object within an array of objects using MongoDB MapReduce JavaScript query? Data example: { "_id": ObjectId("544ae3de7a6025f0470041a7"), "name": "Bundle 4", "product_groups": [ { "name": "camera g ...