Nearpoint
Nearpoint

Reputation: 7362

How to set CSS of one element depending on another element having a specific class?

I have a sidebar menu on my website that opens and closes.

When the sidebar is open I add an additional class called 'active' to the menu button which triggers the menu.

When this menu button element has the class 'active' & screen width is > 768px, I want to set the padding on the element with class 'container-fluid'.

I currently do this with coffeescript/javascript:

@setPaddingIfMenuOpen = () ->
  console.log 'set padding if menu open called from layout coffee'
  if $(window).width() > 768
    if $('.show-left').hasClass 'active' 
      padding = 280
      $('#main > .container-fluid').css 'padding-left', padding
    else 
      $('#main > .container-fluid').css 'padding-left', '25px'
  else 
    $('#main > .container-fluid').css 'padding-left', '25px'

But I was wondering if I could achieve the same thing with pure CSS?

Here is a JSFiddle:

http://jsfiddle.net/685Vv/5/

Once you click the open menu button and the element #showLeft also has class 'active, see if you can get the attribute 'padding-left: 100px' added to the element with class 'main'. And then if the attribute #showLeft does not have the class 'active' then the attribute padding-left should be changed to 'padding-left: 0px'

Upvotes: 0

Views: 209

Answers (1)

m90
m90

Reputation: 11822

You can use CSS Media Queries in case you are able to apply your .active class (or any other class) to some shared parent element - body probably - as well (in case your markup has to stay the way it is you're out of luck I guess).

So in case an expanded side menu would also result in body.side-menu-active you could just do:

#main > .container-fluid{
  padding-left: 25px;
}
@media all and (min-width: 768px){
  .slide-menu-active #main > .container-fluid{
    padding-left: 280px;
  }
}

Upvotes: 1

Related Questions