Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical align using jquery for all devices?

I found as problematic thing to align vertically some elements on page, without changing some others elements layouts.

The problem is magnified on mobile devices. So many screen sizes, resolutions, portrait, landscape...

var x=window.innerHeight - $('#myDiv').height();
    $('#myDiv').css ('margin-top', x/2);

This should be ok for all devices, mobile and desktop. Do you see any downside of these approach?

As I understand, all devices today support JavaScript. But, is it possible that some device supports JS but doesn't support jQuery ?

like image 343
qadenza Avatar asked Mar 07 '26 08:03

qadenza


1 Answers

You should use $('#myDiv').parent().height() instead of window.innerHeight, Because if your #myDiv element was wrapped by another element, your approach may not work correctly.
Also you can encapsulate your codes into a jQuery plugin, like this:

jQuery.fn.verticalAlign = function ()
{
    return this
            .css("margin-top",($(this).parent().height() - $(this).height())/2 + 'px' )
};

Then you can use it like:

$('#myDiv').verticalAlign();

is it possible that some device support JS but doesn't support jQuery ? No, All devices that support a proper version of JS must sopport jQuery, Because the core of jQuery is pure JS
But if you want to align your element vertically in browser screen, You may use the following instead:

jQuery.fn.verticalAlignScreen = function ()
{
    return this
            .css("position", "absolute")
            .css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
};
like image 172
frogatto Avatar answered Mar 10 '26 00:03

frogatto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!