Tips on prefixing Bootstrap 4 classes to prevent conflicts with CSS classes

Recently, I've been focusing on creating small applications for websites. The websites hosting these apps may or may not use a css framework. To prevent any potential conflicts, I have decided to add a unique prefix to all Bootstrap classes. For instance, instead of using the standard col- classes, I will now be using year19-col-, and similar modifications for other Bootstrap classes like .btn which would become .year19-btn, .year19-btn-primary, etc...

In cases where we utilize sass themes to create new classes, we can avoid some conflicts by generating our own prefixes through theming. However, when it comes to JS frameworks, conflict resolution is trickier, especially if multiple versions exist on the same page. While there was a Github project for Bootstrap 3 that allowed users to easily add their custom prefixes, this feature seems to be missing in Bootstrap 4.

I also prefer not to encapsulate the entire project within a css class as a solution. Although this method works for certain scenarios, it doesn't truly address the core issue at hand. In my opinion, true namespace implementation involves not just wrapping the classes with a container but actually modifying the class names themselves.

For example: .year19-btn-primary { this code block will remain untouched from its original functionality. }

Answer №1

I successfully implemented prefixing for Bootstrap 5.1.3 classes. Before compiling Bootstrap on your own, you'll need to make the following adjustments. You can find my complete implementation here: https://github.com/Robpol86/sphinx-carousel/tree/85422a6d955024f5a39049c7c3a0271e1ee43ae4/bootstrap

package.json

"dependencies": {
  "bootstrap": "5.1.3",
  "postcss-prefix-selector": "1.15.0"
},

To utilize postcss-prefix-selector in postcss, you need to add postcss-prefix-selector as shown above.

postcss.config.js

'use strict'

const prefixer = require('postcss-prefix-selector')
const autoprefixer = require('autoprefixer')
const rtlcss = require('rtlcss')

module.exports = ctx => {
  return {
    map: ctx.file.dirname.includes('examples') ?
      false :
      {
        inline: false,
        annotation: true,
        sourcesContent: true
      },
    plugins: [
      prefixer({
        prefix: 'scbs-',  // ***REPLACE scbs- WITH YOUR PREFIX***
        transform: function (prefix, selector) {
          let newSelector = ''
          for (let part of selector.split(/(?=[.])/g)) {
            if (part.startsWith('.')) part = '.' + prefix + part.substring(1)
            newSelector += part
          }
          return newSelector
        },
      }),
      autoprefixer({
        cascade: false
      }),
      ctx.env === 'RTL' ? rtlcss() : false,
    ]
  }
}

The CSS prefixing is done using postcss instead of just wrapping bootstrap.scss with a class/id selector. This setup allows me to use the Bootstrap 5 carousel component on Bootstrap 4 websites. The provided link will replace the official Bootstrap postcss configuration file.

rollup.config.js

// ...
const plugins = [
  replace({ // ***COPY/PASTE FOR OTHER BOOTSTRAP COMPONENTS***
    include: ['js/src/carousel.js'],  // ***YOU MAY NEED TO REPLACE THIS PATH***
    preventAssignment: true,
    values: {
      'CLASS_NAME_CAROUSEL': '"scbs-carousel"',  // ***USE YOUR PREFIXES HERE***
      'CLASS_NAME_ACTIVE': '"scbs-active"',
      'CLASS_NAME_SLIDE': '"scbs-slide"',
      'CLASS_NAME_END': '"scbs-carousel-item-end"',
      'CLASS_NAME_START': '"scbs-carousel-item-start"',
      'CLASS_NAME_NEXT': '"scbs-carousel-item-next"',
      'CLASS_NAME_PREV': '"scbs-carousel-item-prev"',
      'CLASS_NAME_POINTER_EVENT': '"scbs-pointer-event"',
      'SELECTOR_ACTIVE': '".scbs-active"',
      'SELECTOR_ACTIVE_ITEM': '".scbs-active.scbs-carousel-item"',
      'SELECTOR_ITEM': '".scbs-carousel-item"',
      'SELECTOR_ITEM_IMG': '".scbs-carousel-item img"',
      'SELECTOR_NEXT_PREV': '".scbs-carousel-item-next, .scbs-carousel-item-prev"',
      'SELECTOR_INDICATORS': '".scbs-carousel-indicators"',
    }
  }),
  babel({
    // Only transpile our source code
// ...

Lastly, the rollup replace plugin is utilized to incorporate prefixes in the compiled javascript file. Instead of merely prefixing consts, the entire const is replaced and hardcoded with full class names. Depending on the Bootstrap components included in your final build, you may need to repeat this process. Fortunately, if only the carousel is needed like in my case, it shouldn't be too burdensome.

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

The z-index of 999 in CSS is not functioning as expected on both Google Chrome and Safari browsers

To ensure the slider text is readable in white color, we have applied a black background with 0.65 opacity CSS on the slider image. This allows the white text to stand out effectively. The following CSS code was used for this effect: .zlslides .ms-slide- ...

What steps can be taken to ensure that the content in column two does not impact the positioning of content in column one?

Is there a way for the input text container to remain in its original position within the layout even after submitting text? Usually, when the data displayed container's height increases, it pushes the input text container down. Despite trying absolu ...

Alignment of Bootstrap 5 card text and buttons

I've been diving into the BootStrap 5 Crash Course from this YouTube link: https://www.youtube.com/watch?v=4sosXZsdy-s. The final website from the tutorial can be found here: One specific part focuses on using Cards, but I'm facing an issue wher ...

What is the best way to collapse the entire navigation menu after clicking a link (nav-link) within it?

I created a navigation menu using HTML and SCSS, but I'm facing an issue where the menu does not close when clicking on links inside it. The menu continues to overlay the content on the page instead of closing. Essentially, I want the navigation menu ...

Steps to show submenus upon hovering over the main menu items

I am trying to create a vertical menu with multiple levels using HTML and CSS. Here is the code I have written so far: <ul> <li>Level 1 menu <ul> <li>Level 2 item</li> <li>Level 2 item</li&g ...

Tips for utilizing dynamic variables when setting props in React Native styles

I am encountering an issue while trying to set props in the stylesheet to dynamically change the background color based on data received from the server. undefined is not an object (evaluating 'this.props.colorCode') Below is the snippet of my ...

Ways to eliminate the dotted line from the image map in Internet Explorer 11

Below you will find the code I am working with: <img alt="Testing 2015" border="0" src="images/Test-2015.jpg" usemap="#Map" /> <p><map name="Map"><area coords="790,100,653,135" href="http://www.google.com/" shape="rect" style="cursor ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

Utilizing Bootstrap's popover feature in conjunction with dynamic content load using jQuery's .on

I am facing an issue with my Yii application that utilizes cgridview and ajax pagination. The common problem encountered is the loss of binding with jQuery after paginating, causing functionalities like popovers to stop working. My current popover functio ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

Guide to aligning a div element along the right edge of the webpage

I'm struggling to align this div all the way to the right side of the screen. Below is the HTML: <html> <head> title></title> <link rel="stylesheet" type="text/css" href="../css/style.css"/> </head> <h1&g ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

Stop jQuery popups from wrapping text when resizing the browser window

Whenever a link is clicked, a jQuery popup appears. The popup functions properly in terms of opening and closing, but I would like to ensure that its position remains fixed when resizing the browser window to avoid any wrapping issues. Typically, I use a ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Using "overflow-x: hidden" is ineffective on mobile devices

I'm facing an issue where the CSS property overflow-x: hidden is not working on mobile devices. Here is a snippet of my HTML code: <div class="topbar"> <div class="navbar-brand float-left"> <a href="#"><img src="asset ...

Errors can be thrown when using React and classNames in the class component

I'm relatively new to React and currently working on a large project. I've run into an issue where I can't use both class and className on all elements and components, particularly custom ones. To work around this, I've had to place the ...

Retrieving CSS properties of an element using JavaScript

How can I efficiently retrieve all CSS rules associated with a specific element using JavaScript? I am not seeking a particular solution, just looking to capture all CSS rules for the given element. For example, consider the following HTML code: <div ...

How come my ejs files are all affected by the same stylesheet?

Currently, I am in the process of developing a nodeJS application utilizing Express, MongoDB, and EJS template view engine. The server.js file has been successfully created to establish the server. In addition, a separate header.ejs file has been implement ...

Reversing the sequence of elements in Bootstrap 4

In my list of 3 elements, the display order is as follows: text - image image - text text - image On mobile devices, I aim to switch the position of the text and image in the second element, but currently, it is the opposite. <div class="container"& ...