简体   繁体   中英

Div centering vertically when mobile page is at top, but when we scroll down the page, error is occuring

I am building a cordova app. When I click on div, its conponents are shown and the popup has to be in the center of screen. This is my code.

        var new_height = $('#' + id).height() + 20;
        var new_width = $('#' + id).width() * 0.97;

        $('#' + id + '_popup').width(new_width);

        var move_up = $('#' + id + '_popup').height() / 2;

        $('#' + id + '_popup').css({
            "overflow-y": 'auto',
            'transform': 'translateY(-' + $('#' + id + '_popup').height() / 2 + 'px)'
        });

        $('#' + id + '_popup').css("z-index", '3000');

But when I scroll the page, the new div is not displaying in the center of div but above. What should I do?

You can achieve perfect center only with CSS, so remove that useless calculations and use transform like this:

 .red { position: absolute; height: 100%; width: 100%; background: red; } .green { position: absolute; height: 40%; width: 40%; background: green; top: 50%; left:50%; -webkit-transform: translate(-50%, -50%); /*safari iOS*/ transform: translate(-50%, -50%); } 
 <div class="red"> <div class="green"> </div> </div> 

With this code doesn't matter the sizes of the boxes, it will be always at the center of the screen.

You can change position to fixed or relative and still will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM