Search code examples
jqueryhtmlcssalignment

CSS: Vertical centering in a position:absolute div


I have this code:

<div class="parent">
    <div class="child">something</div>
</div>

The parent should be 200px width and height, and the child 100px width and height. The parent is also set to position:absolute. Is it possible to horizontaly and verticaly center the child relative to the parent and how?

The result: If you set black background to the parent and white to the child, the whole thing should look like there is a white square with a large black border.

Static margins and paddings are out of the question since the size of the child will change dynamically.


That might not be the proper solution, but what I am actually trying to achieve is a black square which I can change the size of with jQuery and it will stay at the same absolute position, like it is being scaled from the center, not from the top left corner.

I thought I could set the position of a parent and let the child center horizontaly and verticaly auto while changing it's size, so I would get the proper 'scale'-like effect.


Solution

  • I used jQuery UI position API to position the child div at center and then on .animate based on border-width you should change the top and left accordingly.

    Try out the DEMO to understand the below code DEMO

    After Animation:

    enter image description here

    HTML:

    <div class="parent">
        <div class="child">something</div>
    </div>
    
    <button>Animate</button>
    

    JS:

    $(document).ready (function () {
        positionChild();
    });
    
    
    function positionChild() {
        $( ".child" ).position({
                    of: $( ".parent" ),
                    my: "center center",
                    at: "center center"
        });
    }
    
    $('button').click (function () {
        $('.child').animate({'border-width': 47, top: '-=46', left: '-=46'}, 1000);
    });
    

    CSS:

    .parent { 
        position: absolute;  
        width: 200px; 
        height: 200px; 
        background-color: black; 
        top: 100px; 
        left: 100px; 
    }
    
    .child { 
        width: 100px; 
        height: 100px; 
        background-color: #c2c2c2; 
        border: 1px solid blue;
    }