Search code examples
javascriptjqueryjquery-uicsscompass-sass

Animate background color from center to corners of a div [Sqaure shaped] using Javascript or css


If possible you guys, can you help me with this animation?, the purpose of animation is to animate a background-color, the color is what i want to animate not the div cause the div contains another elements that I want to be always showing. The animation i'm looking for is to spread the color[gray of containing div] from center to corners of a square. is there a way to do it in CSS, if not how about Javascript/Jquery/Jquery-ui? maybe sass or compass? I'm fine with any of the above here's a jsfiddle and the code:

HTML:

     <div class="outer_box">
       <div class="inner_box_1"></div>

       <div class="inner_box_2"></div>

       <div class="inner_box_3"></div>

       <div class="inner_box_4"></div>
    </div>

a simple CSS that might help:

  .outer_box{
    background-color: gray;
    width: 400px;
    height: 400px;
   }
  .inner_box_1{
    background-color: yellow;
    width: 50px;
    height: 50px;
   }
  .inner_box_2{
    background-color: green;
    width: 50px;
    height: 50px;
   }
  .inner_box_3{
    background-color: blue;
    width: 50px;
    height: 50px;
   }
  .inner_box_4{
    background-color: orange;
    width: 50px;
    height: 50px;
   }

Solution

  • Am assuming that you do not require a gradient.

    There could be pure CSS3 solutions, but this is the easiest hack I could think of using jQuery.

    See this fiddle: http://jsfiddle.net/pyf4P/2/

    You give a position: relative and transparent background to your outer_box div:

    .outer_box {
        background-color: transparent;
        width: 400px; height: 400px;
        position: relative;
    }
    

    Then, have a dummy div inside that container and give it position:absolute starting from center, and with lower z-index than the container, and with your desired background color:

    Markup:

    <div class="outer_box">
        <div class="inner_box_1"></div>
        <div class="inner_box_2"></div>
        <div class="inner_box_3"></div>
        <div class="inner_box_4"></div>
        <div id="dummy"></div> <!-- this is the dummy -->
    </div>
    

    CSS:

    #dummy { 
        position: absolute;
        top: 200px; left: 200px;
        width: 1px; height: 1px;
        background-color: gray;
        z-index: -5;
    }
    

    That's it. Now you can animate this dummy div using jQuery:

    $('#dummy').animate({
        'width': '400px',
        'height': '400px',
        'top': '0px',
        'left': '0px'
    }, 500);
    

    Hope that helps.