sadek sadek - 18 days ago 6
CSS Question

How can I apply css on a nested element

My title of the question doesn't seem to be right as I couldnot find a right title.

I am using a owl cursol in my html. See the html code

<div role="tabpanel" class="tab-pane fade in active" id="ios">
<ul class="screenshot-carousel">
<li class="item"><img class="im" style="margin-left:1px;" src="images/screenshot1.jpg" alt="Image"></li>
</ul>
</div>


the class active get removed when the image in the center. So what I wanted to do is, when the div has class name active I want to apply a margin-top:-36px to img with the class name "im" and when there is no active class I want to apply margin-top 0px.

I tried this jQuery code to achieve that but doesn't work...

<script>
$(document).ready(function(){
var hasClass= $("div").hasClass("active");
if(hasClass){
$(".im").css("margin-top","-36px");
}
});

</script>

Answer

So what I wanted to do is, when the div has class name active I want to apply a margin-top:-36px to img with the class name "im" and when there is no active class I want to apply margin-top 0px.

You do that with CSS: Put the class im on the img, and then use this CSS to control the margin-top:

.im {
    margin-top: 0px;
}
.active .im {
    margin-top: -36px;
}

Simplified example:

document.querySelector("input[type=checkbox]").addEventListener("click", function() {
  document.querySelector(".container").classList.toggle("active", this.checked);
  var img = document.querySelector(".img");
  var style = window.getComputedStyle ? getComputedStyle(img) : img.currentStyle;
  console.log("\"Image\"'s margin-top is now: " + style.marginTop);
}, false);
.im {
    margin-top: 0px;
}
.active .im {
    margin-top: -36px;
}

.container {
  border: 1px solid #ddd;
  height: 80px;
  min-height: 80px;
}
.img {
  border: 1px solid green;
}
<div class="container">
  This is the container
  <div class="img im">
    This is the "image"
  </div>
</div>
<label>
  <input type="checkbox">
  Make the container "active"
</label>