NickD NickD - 4 months ago 11
CSS Question

how to hide div when the front div is smaller

Is there any way to hide a div when the front div is smaller.
I want to animate a black box left but be visible when comes through the left side of green box.
i tried overflow-x: hidden with no luck..

enter image description here

Another question.
Can i use jquery toggle() to green box? i tried .toggle("slide"), black box goes slide left but also executes a zoom out too..

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#green").click(function(){
$("#black").animate({left: '-250px'});
});
});
</script>
</head>
<body>
Click on green box to animate black one
<div id="green" style="background:#98bf21;height:100px;width:100px;position:absolute;margin-left:300px;z-index:10;overflow-x: hidden;"></div>
<div id="black" style="background:#1d1d1c;height:100px;width:260px;position:absolute;margin-left:300px;z-index:1;"></div>




Answer
  • Use a 100x100 #parent with overflow hidden that will contain your two elements.
  • Position #green at right:0 and #black at the parent's right:100px.
  • On #parent click animate parent width (using CSS3 if you want)

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<style>
  #parent {
    position: absolute;
    right: 0px;     /* position parent wherever you want */
    height: 100px;
    width: 100px;
    overflow: hidden;
    /* contain children elements */
    /* basivcally all same as green DIV initially...*/
    transition: 0.4s;
    -o-transition: 0.4s;
    -ms-transition: 0.4s;
    -moz-transition: 0.4s;
    -webkit-transition: 0.4s;
  }
  #parent.enlarge {
    /* Added by jQuery on click */
    width: 360px;  /* 260 + 100 */
  }
  #green {
    background: #98bf21;
    height: 100px;
    width: 100px;
    position: absolute;
    /*margin-left: 300px;*/
    right:0; /* position at parent right 0 */
    /*z-index: 10; you don't need Z index ins you place HTML order properly */
    overflow-x: hidden;
  }
  #black {
    background: #1d1d1c;
    height: 100px;
    width: 260px;
    position: absolute;
    right: 100px; /* position at parent right 100px */
    margin-left: 300px;
  }
</style>


<body>

  Click on green box to animate black one
  <div id="parent">
    <div id="black"></div> <!-- invert order to prevent z-index in CSS -->
    <div id="green"></div>
  </div>

  <script>
    jQuery(function($) {
      $("#parent").click(function() {
        $(this).toggleClass("enlarge");
      });
    });
  </script>
</body>

</html>