Home > database >  how to check if a class having a css property and change other class' css property based on tha
how to check if a class having a css property and change other class' css property based on tha

Time:10-27

like in this example, if sidebar class has width:0; then change content class' margin-left from 60px to 0 here is the code for reference:

.sidebar{
    width: 0px;
}
.sidebar-open{
    width: 60px;
}
.content{
    margin-left: 60px;
}
<div class="wrapper">
    <div class="main d-flex">
        <div class="sidebar ">
            <ul>
                <li>Home</li>
                <li>Dashboard</li>
                <li>Contact Us</li>
                <li>About us</li>                   
            </ul>
        </div>
        <div class="content flex-fill"></div>
    </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Generally speaking, you can use CSS selector specificity (good reads here and here) in order to override some styles based on some conditions such as markup structure, screen size, etc.

In particular to your example, you can exploit the fact that the content element is right after the sidebar element in the DOM, and make use of the CSS operator which targets an element matching the 2nd part of the selector (after the ) only if it appears immediately after an element matching the 1st part. Like so:

.sidebar   .content {
    margin-left: 0;
}

Adding this rule inside your <style> tag will apply margin-left: 0; to .content only if .sidebar is rendered right before it, and being a more specific selector, it will override the initial .content declaration. You will see in the Elements panel of your Developer Tools that the margin-left: 60px; rule is crossed out.

Also, to apply the margin only when the sidebar is open, you could use the same technique like this:

.sidebar.sidebar-open   .content {
    margin-left: 60px;
}
  • Related