How to set my div element to the center of the screen using jquery

so how to set the left and top. (even if I scroll scrollBar)

thank

+3
source share
7 answers

the machine elf and Stefan Kendall are both very close, but both are incomplete, so you simply combine them like this (the machine elf did not take into account the scroll bars, and Setfan did not take into account the height and width of the div itself):

Assuming your id for your div is "myDiv"

$('#myDiv').css('position','fixed');
$('#myDiv').css("left", ($(window).width()/2-$('#myDiv').width()/2) + "px");
$('#myDiv').css("top", ($(window).height()/2-$('#myDiv').height()/2) + "px"));

You may also need to set the css of your div to the height and width of the patch, and its display is set to "block". You can do this with jQuery.

In addition, you can combine all this into one long string.

+2
source

@wag2639 , , @machine elf, , .

$(window).scroll(function () { 
   $("#your_obj").center();
});
+1

jQuery, CSS, position:relative; left:-50% position:relative; left:50% . , CSS, .

. http://www.pmob.co.uk/pob/centred-float.htm.

+1

...

$('#myDiv').css('position','absolute');
$('#myDiv').css("left", ($(window).width()/2-$('#myDiv').width()/2) + "px");
$('#myDiv').css("top", ($(window).height()/2-$('#myDiv').height()/2) + "px"));

- . . .

0

, :

: CSS: : ?

jQuery (# 17): 20 jQuery jQuery

0

, , , CSS position: fixed; ( jQ $('#myDiv').css('position','fixed'); , ) :

jQuery : fixed ( ) div?

0
jQuery.fn.center = function () {
    var w = $(window);
    this.css("position","fixed");
    this.css("top",w.height()/2-this.height()/2 + "px");
    this.css("left",w.width()/2-this.width()/2  + "px");
    return this;
}
$("#your_obj").center();
0

Source: https://habr.com/ru/post/1737770/


All Articles