Home > Mobile >  How to apply css property on a descendent class where the parent class is being toggled?
How to apply css property on a descendent class where the parent class is being toggled?

Time:05-31

I need to apply some css on a div whose parent div's class toggles based on a class. I want to apply some css on the child div. The parent div has classes as .pricing-section and .new-pricing-section. They are toggeled based on a flag. The complete parent div is as follows:

const togglePriceSection = isPricingDetailsFeatureEnabled ? "new-pricing-section" : "pricing-section";
<div className={togglePriceSection}>
    <div className="btn btn-link btn-icon show-more-link" onClick={() => setExpanded(!expanded )}>
                        {pricesList.length > 6 && !expanded ? "Show More" : expanded ? "Show Less" :null}
                    </div>
</div>

I want to apply css to the div with btn class. I was doing it like this:

.pricing-section, .new-pricing-section .btn.btn-link.show-more-link {
    text-transform: none;
    margin-left: auto;
}

The problem is these properties are applied only when the parent div has className=".new-pricing-section", and not when className=".pricing-section". I want it to get applied in both the cases. How to fix this?

CodePudding user response:

The comma means this is a new selector. You actually have a bug here, it seems.

This will apply to .pricing-section and .new-pricing-section .btn.btn-link.show-more-link

.pricing-section, 
.new-pricing-section .btn.btn-link.show-more-link {
    text-transform: none;
    margin-left: auto;
}

You really want to apply to .pricing-section .btn.btn-link.show-more-link and .new-pricing-section .btn.btn-link.show-more-link

.pricing-section .btn.btn-link.show-more-link, 
.new-pricing-section .btn.btn-link.show-more-link {
    text-transform: none;
    margin-left: auto;
}

That said, it may be cleaner to separate the new out into an extra class. So you have the below for the button.

.pricing-section .btn.btn-link.show-more-link {
    text-transform: none;
    margin-left: auto;
}

And everything that relies on this being a new pricing section, you have pricing-section new as classList. That one you can select with .pricing-section.new.

CodePudding user response:

.pricing-section .btn.btn-link.show-more-link {
    // css if child is under pricing-section
}
.new-pricing-section .btn.btn-link.show-more-link {
    // css if child is under new-pricing-section
}

CodePudding user response:

You need to change slightly your selection, as what you did means select the parent when it has pricing-section and the child when the parent has the class new-pricing-section:

.pricing-section .btn.btn-link.show-more-link, .new-pricing-section .btn.btn-link.show-more-link {
    text-transform: none;
    margin-left: auto;
}
  • Related