Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply/remove CSS class if parent has specific class

Tags:

html

css

Is it possible in CSS 3 to apply/remove a certain css class (not property/value) to an element based on it's parent class?

I'll give a concrete example to try and better explain my meaning - say I have a <div> which depending on circumstances I may apply the style-class my-large-div or my-small-div. Inside it, I some inputs/buttons with the Bootstrap class form-group and form-group-lg:

<div class="my-large-div">
    ...
    <div class="my-form-group form-group form-group-lg">
        <!-- some input field -->
    </div>
</div>

Now, what I want to happen is that when my-large-div is applied, the inner div will have form-group-lg, but when my-small-div is applied, it will not. I conceptually think of a CSS like this:

.my-large-div .my-form-group {
    add-class("form-group-lg");
}

.my-small-div .my-form-group {
    remove-class("form-group-lg");
}

Now, I know this can be achieved using Javascript/jQuery, but I'm looking for a CSS-only solution, if such a solution exists, or a definitive answer that it can't be done.

One possible solution would be to always have two copies of my-form-group, with display set to either none or initial, but I feel this may be messy as well as inefficient (If, say, I change the class in response to user's actions in the page).

One thing I certainly don't want to do is to replicate the entire definition of form-group and form-group-lg in my own CSS, as that would mean with every change of the Bootstrap classes I will have to change mine (plus it breaks the abstraction).

like image 234
Itai Avatar asked Sep 14 '26 14:09

Itai


1 Answers

Yeah by using the :not() selector you can do something like

.form-group-lg {
    display: none;
}

.my-form-group:not(.my-small-div) .form-group-lg {
    display: block;
}

What this does is check if the div with the class my-form-group also has a class my-small-div, if it doesn't, form-group-lg will be displayed as a block, else it will just be display: none;

like image 158
Meers E. Chahine Avatar answered Sep 16 '26 07:09

Meers E. Chahine