Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left.

I am using create-react-app with babel/webpack and react-bootstrap.

Since importing conditionally is not possible, I have implemented a conditional require in my code:

if (language.isLanguageLTR()) {
    console.log("REQUIRE RTL CSS");
    require("./rtl.css");
}

While this setup works fine in development mode, I face an issue when building my application using create-react-app - the css file gets imported even if the condition evaluates to false.

Is there a way (which I believe exists!) to override specific css classes without resorting to inline styles or adding special classes everywhere I use bootstrap columns?

I suspect webpack behavior might be the culprit during deployment, but I don't fully understand why. Perhaps there is a better approach to conditionally overriding css.

Below is a snippet of my custom css for reference:

.App {
  direction: rtl;
}
.col-sm-1 {
  float: right;
}
.col-sm-2 {
  float: right;
}
...

Answer №1

After some investigation, I discovered that when using a conditional import/require in webpack, the file is always inserted to ensure it is available if needed. This caused an issue when importing a css file as it overrode existing styles. To solve this problem, I ended up defining the css styles using pure javascript (similar to this solution: ) and surprisingly, it worked well on Chrome, Internet Explorer, and Firefox. Although not the most aesthetically pleasing approach, it was effective and did the job. Ideally, I would prefer having the styles in a separate .css file, but for now, this solution suffices.

    var style = document.createElement("style");
    style.appendChild(document.createTextNode(""));
    document.head.appendChild(style);

    style.sheet.insertRule(".App { direction:rtl; }", 0);
    style.sheet.insertRule(
        ".col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7,  .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12  {float: right;}",
        1
    );`

Answer №2

In my opinion, the most efficient method to achieve your desired outcome is by implementing a float: right class that can be dynamically added using jQuery. Here is an example:

// CSS
.rtl {
    float: right !important;    
}

// Javascript
var isLTR = true;
function changeDirection( isLTR ) {
    $( '.col-sm-1, col-sm-2' ).addClass( 'rtl' );
}

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

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

Accordion section appears on the webpage as it is loaded

I am currently working on implementing an accordion feature for my webpage. Everything is functioning correctly when I click the button, but there is one issue - the div opens automatically when the page loads. My goal is to have the div closed initially a ...

Leveraging JQuery for form submission

My webpage contains a form with the following structure: <form action="/" method="post"> <select id="SelectedMonth" name="SelectedMonth"> <option>7/1/2017</option> <option>6/1/2017</option> </select> </form> ...

Scrolling animations do not support the Translate3d feature

I'm struggling to implement a smooth scroll effect on the header of my website. My approach involves using transform:translate3d for animation, with the goal of keeping the header fixed at the top and moving it out of view as the user scrolls down. I ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Flashing images with jQuery Flickrush - Encasing the image within <li> tags

I have a div with an unordered list inside: <div id="flickr"> <ul></ul> </div> Currently, I am utilizing a plugin found at this link. To make it functional, I've included the following Javascript code: $(function() { $( ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

Adjust the height of an element using CSS based on the height of another

Is there a way to have two divs per row, where the second div always displays its full content and the height of the first div matches the height of the second div? If the content in the first div exceeds the height, it should be scrollable. I've atte ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

Saving Selected Radio button values into Jquery Array

In my HTML table, there are multiple rows with radio buttons representing the sexes in the 0th position of <td>. I am trying to store the values of sex (either 1 or 0) in an array. Below is a snippet for a table with 3 rows. HTML Code: <table> ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Are there any methods to alter the location where Material-UI inserts its style tag html elements?

When it comes to adding style tags, Material-UI usually does so within the <header />, which is a common practice. However, I am in need of a way to insert my style tags into a different HTML element. My current challenge involves transitioning an o ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

What is the best way to create a box-shadow with an inset effect and a touch of

Looking to dive into the world of css3 design and wondering how to achieve a box-shadow inset with a touch of transparency. Check out the example in this fiddle link: http://jsfiddle.net/TeGkt/4/ Any ideas on how to replicate this effect without relying ...

Gradually blend the section of the picture with an image banner after 20 seconds

I have a background image that rotates every 20 seconds, fading in and out. The images consist of a logo at the top-left corner and a person image at the right side from top to bottom. However, I want only the person image to fade in and out while keeping ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

Scan for every header tag present and verify the existence of an id attribute within each tag. If the id attribute is absent, insert

Looking to locate all header tags within the content and verify if each tag has an id attribute. If not, then jQuery should be used to add the id attribute. Here is the code snippet: var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); $.each( ...

Substitute the value in the object associated with a mystery key with a different value from the second object

I am dealing with the following objects: http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 } input= {"phone": "2", "id": "258 }, Can someone help me find the #phone# val ...

Why does this element on Safari have a focus outline appearing even before it is clicked?

The issue is occurring specifically in Safari, and you can see it firsthand by clicking the "chat now" button located in the lower right corner of the screen: Upon clicking the "chat now" button, the chat window's minimize button displays a focus out ...