What are alternative ways to divide CSS without relying on CSS-in-JS and CSS modules?

Recently, I transitioned to next.js and I'm eager to develop an application with CSS styles without resorting to css-in-js or inline styling. In my exploration, I've come across two potential options: using CSS modules or importing global styles in _app.js. The distinction between the two can be summarized as follows:

  • CSS modules are loaded only when the components utilizing them are loaded, thereby maintaining local scope.
  • Global styles, on the other hand, are loaded all at once and lack a local scope.

Initially, I considered employing CSS modules due to their ability to load styles selectively based on necessity. However, I encountered challenges related to overriding styles and dealing with specificity issues. As an illustration, consider a Button component that contains an icon. While the default state of this Button includes certain stylings, a navigation Button might require a slightly altered appearance with a different icon size. In the case of global styles, one could use the following structure:

<div class="navigation">
    <button class="navigation__button button button--modifier">
        <img class="button__icon" />
        <span class="button__text">Click me!</span>
    </button>
</div>

...where button, button--modifier, button__icon, and button__text represent class names for the default styles of the Button component. Meanwhile, navigation__button is utilized to adjust the button specifically for navigation, potentially leveraging inheritance to modify the icon's style:

.navigation__button .button__icon {
    width: 24px;
}

However, when working with CSS modules, it becomes challenging to override styles if they are defined in another .module.css file (such as Navigation.module.css). Overcoming this obstacle may require tactics like implementing the :global selector or adding specificity through alternative means, leading to increased complexity and potential conflicts.

How do developers typically navigate these challenges when utilizing CSS modules? Is there a way to separate stylesheets without relying on CSS modules or css-in-js?

Edit: Are there significant performance or loading speed discrepancies between bundling all stylesheets together, as seen with global styles, versus loading modules within components?

Answer №1

Benefits of BEM

  • Utilizing a strong class naming convention can eliminate the need for using modules (which appears to already be implemented in your project)

  • For insights on implementing the BEM naming convention in React or Next.js, check out this guide and this article

  • You can also achieve style separation by defining styles in separate files

  • Have you explored the use of SASS or SCSS as well?

Enhancing Styles with SASS / SCSS

  • Learn about SASS with this introductory resource

  • Compare examples of SASS, SCSS, and CSS styling with this guide

  • Combining SASS or SCSS with BEM naming can streamline styling by utilizing nesting features

For instance, consider transforming your code structure to include components like Navigation:

<div class="Navigation">
    <button class="Navigation__button Navigation__button--modifier">
        <img class="Navigation__button__icon" />
        <span class="Navigation__button__text">Click me!</span>
    </button>
</div>

An example SCSS file could look like this:

.Navigation__button {
  
  // button styling

  &--modifier {
    // modifier styling
  }

  &__icon {
    // icon styling
  }

  &__text {
    // text styling
  }
}

Considerations for CSS Styling

  • If sticking with pure CSS, nesting may still be an option depending on browser compatibility. Review the support details on Can I Use
  • The concept remains similar to SASS/SCSS but with slightly different syntax - refer to this resource for more information

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

Connection to localhost at port 3001 is being denied

While busy with a project, I encountered an issue where my localhost3001 was constantly refusing to connect. Any ideas on how to resolve this? Check out the image of the problem here. Even after attempting to run my app, localhost3001 still refused to con ...

Togglebox CSS is set to hide elements initially

I am having issues with Lightbox2 as it is not functioning properly when I try to click on the image. Upon inspecting the Developer Console in Chrome, I noticed that the overlay and image are being added to the DOM, but the display property is set to none ...

Switching to a night mode in Material UI theme within a React Context

I'm having trouble implementing a dark mode toggle feature for my web app. I am utilizing NextJS with Material UI. I attempted to create a React context that includes a useState and have a switch component modify the context. theme.tsx This is wher ...

After converting my HTML elements to JSX in Next.js, I am experiencing issues with my CSS files not being applied

Hey there, I'm currently working on a website using Next.js. I've converted the HTML elements of a page to JSX elements but for some reason, the CSS of the template isn't showing up. I've double-checked all the paths and even updated th ...

Issue "Invalid UTF-8" encountered while compiling sass using @import

Here is the structure of my project: project assets scripts styles app.scss bower_components node_modules public css app.css js bower.json gulpfile.js package.json I am using gulp-sass to compile app.scss into ap ...

The navigation and title refuse to align in the center

Learning coding from scratch is a challenge, especially when tasked with creating a website for school. Right now, I'm gradually getting the hang of it, but I am struggling to center my navigation and title. Everything looks fine on my 13-inch laptop, ...

What are the steps to enable CSS code completion for JavaFX again?

Hello everyone, Recently, I disabled the CSS code completion feature for JavaFX-Tags such as '-fx-...'. Unfortunately, I'm not sure how or why it happened but now I would like to enable the code suggestions again. I have been unable to loca ...

What is causing my nested class to be treated as a sibling rather than a child in HTML code

I have been searching for a clear answer to my query, but haven't found one yet. In my HTML script, I have nested divs structured like this: <ul id="navbar"> <li><a href='#' class='dropdown'>Rules</a> ...

Arranging data into columns using HTML and CSS

I'm currently working on a CSS solution to organize various elements like buttons and text in a tabular column format. My main challenge lies in controlling the layout effectively, especially since CSS columns are not compatible with IE9 and earlier v ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

The parameter necessary for [Route: admin.request.update] is missing. The required URI is admin/request/{request}, and the missing parameter is 'request'

When attempting to access detail.blade.php, I encountered an error stating "Missing required parameter for [Route: admin.request.update] [URI: admin/request/{request}] [Missing parameter: request]." Despite following the steps and codes exactly as in my pr ...

Even after applying the CSS property "resize:none" to my HTML textarea, I still find it to be adjustable in size when viewed in the Opera browser

I'm currently working on customizing my HTML page and I want to ensure that all text inputs are consistent in size. I attempted to use the text-area selector in CSS, but it didn't seem to work correctly in Opera. The resize handle disappeared in ...

Fixing a menu hover appearance

I recently encountered a small issue with the menu on my website. When hovering over a menu item, a sub-menu should appear. However, there seems to be a slight misalignment where the submenu appears a few pixels below the actual menu item. Check out the w ...

What is the process for creating a global variable in JavaScript?

Having trouble changing the value of "invocation_num" within a loop? I attempted to modify it as follows, but ended up with an undefined value. Any help would be greatly appreciated. $(document).on("click", '.favoret', function(){ document ...

The `d-flex flex-column` is causing the image within the div to be hidden

The setup looks like this: <div className="d-flex flex-column"> <div> Text </div> <div style={{ backgroundImage: 'url(...)' }}> </div> </div> The URL is functioning correctly. The div element is ...

Learn the process of using calc to rotate images on hover with CSS and Jquery

Is there a way to implement the rotate on hover function for images, similar to what is seen on this website under 'our Latest Publications'? I attempted using calc and skew, however, I was unsuccessful in achieving the desired hovering effect o ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

The min-width of 100vh is functioning properly on mobile devices, however, it is not working as expected on PCs when set to 100

When using 100vh, it only works on mobile or if you narrow the width of your web browser on a PC. If the window/width is set at 100%, the image may appear too tall and cause the div class "mars" to overflow the viewport. Unfortunately, screenshots cannot ...

Is there a way to eliminate the space between the content inside a table cell and its borders?

I am struggling with a table setup that includes three columns and multiple rows. The first column contains an image, causing the cells in that row to resize based on the image size. When text is added to the 2nd and 3rd columns, it automatically centers w ...