Larger div centered inside smaller div

前端 未结 3 1230
鱼传尺愫
鱼传尺愫 2021-02-08 00:47

I have a div (#containment) inside another div (#edit). The outer div is smaller. The inner div\'s size will be changed by some jQuery code.

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 01:29

    The child

    should have the following CSS properties

    position: relative;
    width: 500px;
    height: 500px;
    left: 50%;
    margin-left: -250px; /* -(width/2) */
    top: 50%;
    margin-top: -250px; /* -(height/2) */
    

    So if you're changing the child div via jQuery then you must re-calculate the margins...

    JSFiddle

    http://jsfiddle.net/gvee/fzAge/5/

    Initialised CSS

    #edit
    {
        overflow: hidden;
    }
    
    #containment
    {
        background-image: url(http://placekitten.com/500/500);
        position: relative;
        left: 50%;
        top: 50%;
        margin-left: -250px;
        margin-top: -250px;
    }
    

    JQuery

    $('#edit').click(function() {
        var newWidth  = 100 + Math.floor(Math.random() * 500);
        var newHeight = 100 + Math.floor(Math.random() * 500);
        // Resize the child div
        $('#containment').width(newWidth).height(newHeight);
    
        // Let's assign a new background too, eh!
        $('#containment').css({'background-image': 'url(http://placekitten.com/' + newWidth + '/' + newHeight + ')'});
    
        // Now re-calculate the margins...
        var newLeftMargin = (newWidth  / -2);
        var newTopMargin  = (newHeight / -2);
        $('#containment').css({'margin-left': newLeftMargin, 'margin-top': newTopMargin});
    });
    

提交回复
热议问题