简体   繁体   中英

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

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?

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 .

.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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM