cancel
Showing results for 
Search instead for 
Did you mean: 

How to include CSS based on condition?

How to include CSS based on condition?

I am trying to include CSS in template file based on condition as below.

These styles hide some external elements in the page which are not at all related to my module.

If it is related to my module's template then I can create a CSS file with classes and add those classes to my template elements based on the conditions.

I even tried using jQuery on load to append classes using a global CSS file but those HTML elements are dynamic. So, my code fails if there is any change in the HTML dynamically.

In Magento 2, is it ok to include inline CSS if it is very small? if not what is the best way to achieve this?

    <?php if (condition1): ?>
        <style>.......</style>
    <?php endif; ?>
    <?php if (condition2): ?>
        <style>......</style>
    <?php endif; ?>


--------
Give Kudos if it helped or if the problem is solved Accept it as a solution

4 REPLIES 4

Re: How to include CSS based on condition?

Hi @kalyanchakri,

 

I guess isn't a good idea to include css inline.

Also, you won't be able to include css with an IF becasue header will be cached.

Is it possible for you to use css classes in some way you can achieve the result including always all those classes?

Maybe you can use some .hide class to remove those elements, adding the class with javascript?

Re: How to include CSS based on condition?

@Damian Culotta thanks for the response.

"Maybe you can use some .hide class to remove those elements, adding the class with javascript?" I tried this exactly but those elements are changing dynamically. Let me tell you the exact scenario.

In product details page of configurable product, we are showing price ranges in a different format and hiding the actual price of the product based on some conditions. The actual price that Magento is showing changes dynamically based on the swatch selection. If I try to do through javascript on page load it is fine but once I select a swatch it is replacing the entire DOM element and hence the classes added through Javascript are vanishing.

The only way I can think of is adding my logic on click of the swatches also. Right now I am not sure which is the right and standard way to achieve this.

--------
Give Kudos if it helped or if problem is solved Accept it as a solution



Re: How to include CSS based on condition?

Hi @Damian Culotta,

Any more suggestions based on my recent reply?

Re: How to include CSS based on condition?

Hi @kalyanchakri,

 

Sorry but I'm out of ideas (I should try to make some code tests to share new insights)