Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS only if class exists elsewhere in code?

So I'd like to only apply a certain CSS if a class exists in the code elsewhere. I was wondering if this is solely possible through css or if I need to use Jquery for this. Do anyone has any thoughts on this? If I need to use Jquery, can you give an example on how that might looks like?

As you can see in my code, what I try to do is apply a margin-top when li.active exists.

Obviously my jsfiddle is not working: http://jsfiddle.net/zt40oa7d/

Or see the code below:

div.navbar {
  background-color: #CCF;
}
ul.box {
  margin: 0;
}
div.text {
  background-color: #FFC;
  padding: 10px;
}
div.page div.navbar ul.box li.active div.text {
  margin-top: 100px;
}
<div class="page">
  <div class="navbar">
    <ul class="box">
      <li class="active"><a href="#">Link 1</a>
      </li>
    </ul>
  </div>
  <div class="text">This the div that should go down due to the submenu ul</div>
</div>
like image 504
RobbertT Avatar asked Feb 12 '23 04:02

RobbertT


2 Answers

Yes its very possible to do this, its called the addClass() method in JQuery and it is used like this

$( "div" ).addClass( "text" );

Which in turns adds this CSS to your element

.text
{
   background-color: #FFC;
   padding: 10px;
}

this will produce the effect shown in this fiddle.

You can also remove it using $( "div" ).removeClass( "text" );

EDIT

You could also check if the active class exists using the hasClass() method in JQuery like this:

if( $("li").hasClass( "active" ) )
{
  $( "#specificDiv" ).addClass( "text" );
}

And your HTML with updates

<div class="page">
  <div class="navbar">
    <ul class="box">
      <li class="active"><a href="#">Link 1</a>
      </li>
    </ul>
  </div>
  <div id="specificDiv">This the div that should go down due to the submenu ul</div>
</div>

Here you are checking if the <li> has the class "active" assigned to it. If it does it will set the css "text" on the element which contains the id "specificID" but wont affect any other divs.

Have a look at what this does here

Read more on the JQuery addClass() method here.

Read more on the JQuery hasClass() method here.

like image 167
Master Yoda Avatar answered Feb 13 '23 19:02

Master Yoda


Using jquery, you can find the length of li element with class .active on document ready, if yes then set the css to div with class .text:

$(function(){
if($('.active').length){
     $('div.text').css(' margin-top',' 100px');
}});

Working Demo

like image 34
Milind Anantwar Avatar answered Feb 13 '23 19:02

Milind Anantwar