简体   繁体   中英

how to check if a class having a css property and change other class' css property based on that class without "jquery"

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>

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

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