Using Jquery to Center a Div on the Screen

Using jQuery to center a DIV on the screen

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

How can a div be aligned center using jquery

Well, 3 method for this:

Method 1 Using css Function of jquery:

$('div').css('text-align','center');

Method 2 Using attr Function of jquery: attr stands for attribute

$('div').attr('align','center');

Method 2 Using prop Function of jquery: prop stands for property

$('div').prop('align','center');

How to position a div element at the center of the ACTUAL screen? (JQuery)

If you're okay with using fixed positioning instead of absolute, you can use something like the following:

jQuery.fn.center = function ()
{
this.css("position","fixed");
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}

$('#myDiv').center();
$(window).resize(function(){
$('#myDiv').center();
});

Demo: http://jsfiddle.net/GoranMottram/D4BwA/1/

Centering a div vertically & horizontally using jQuery

I normally use this "technique":

$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});

UPDATE:

I'm updating the solution, as suggested by the user Fred K, using .outerWidth() and .outerHeight() to have a more precise centering.

$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});

Some additional notes from jQuery' documentation (.outerWidth(), .outerHeight()):

  • The number returned by dimensions-related APIs, including .outerWidth(), may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.

  • The value reported by .outerWidth() is not guaranteed to be accurate when the element's parent is hidden. To get an accurate value, you should show the parent first, before using .outerWidth().


UPDATE 2:

A simple update to show how you could use this inside the css() method in case there are more elements with the same class tag with different sizes.

$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});

Dynamically center div vertically and horizontally using jQuery

This will calculate dynamically the and position the .box at the center of the screen. You can also call this function on resize and rotate events.

$(updateBoxDimension);
$(window).on('resize', updateBoxDimension);

function updateBoxDimension() {
var $box = $('.box');

// To center the box
var boxLeft = ($(window).width()) / 2 - ($box.width() / 2),
boxTop = ($(window).height()) / 2 - ($box.height() / 2);

$box.css({
left: boxLeft,
top: boxTop
});
}

Demo: https://jsfiddle.net/tusharj/a5Lpeoux/1/

Trying to position a DIV at center of browser viewport window using jquery animate function

This can be solved with simple CSS3.

You are currently positioning the top left corner of your element in the center of the screen. Either you can add a bunch more code to your js. Or add these 5 lines of CSS

#UPSContainer{
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}

DEMO


EDIT: cross browser using negative margins

An alternative is to use negative margins on the fly div. Note that this option only works if you know what the end height and width of your element is going to be (appears you're setting it in the animation anyways)

$(document).ready(function () {
$("#Button1").click(function () {
$("form #UPSContainer").each(function () {
$(this).remove();
});

$('form').append('<div id="UPSContainer" class="hidden" style="background:red;display:none;position:absolute"></div>');
if ($("#UPSContainer").exists() == true) {
$("#UPSContainer").css({ height: 0, width: 0, display: 'block' });

var xleft = ($(window).width() - $("#UPSContainer").width());
var xtop = ($(window).height() - $("#UPSContainer").height());

$("#UPSContainer").css({ left: xleft, top: xtop });
$("#UPSContainer").animate({
left: (($(window).width() - $("#UPSContainer").width()) / 2) + 'px',
top: (($(window).height() - $("#UPSContainer").height()) / 2) + 'px',
height: 100 + 'px',
width: 100 + 'px',
marginLeft: '-50px',
marginTop: '-50px'
}, 200,
function () {
//$("#feed_dialog").removeClass("BusyStyles").find('#acloginpod').fadeIn(2000);
});

}
return false;
});


jQuery.fn.exists = function () { return this.length > 0; }
});

DEMO


EDIT: request for a way to toggle the box open and closed

I have significantly changed your code. I have done this as there was going to be a whole lot of repeated steps if i were to just use the code you supplied. The caching of jQuery DOM searching, data attributes to store global variables, updates to allow for window resizing, single DOM insertion of elements, were all done in an attempt to write speedy jQuery code.

You can now have multiple buttons to open/close the overlay.. just give them the class toggleUPSContainer

$(document).ready(function () {
var $els = [];
var data = {
"UPSContainer": {
"height" : 100,
"width" : 100
},
"isAnimating" : false
};
$els.window = $(window);
$els.form = $('#ctl00');
$els.toggleUPSButtons = $('.toggleUPSContainer');

function addUPSOverlay(){
$els.form.append('<div id="UPSContainer"></div>');
$els.UPSContainer = $('#UPSContainer');
}

function getNewWindowCorner(){
data.windowWidth = parseInt($els.window.width());
data.windowHeight = parseInt($els.window.height());
if($els.UPSContainer.is(':hidden')){
$els.UPSContainer.css({
top: data.windowHeight + 'px',
left: data.windowWidth + 'px'
});
}else{
$els.UPSContainer.css({
left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px'
});
}
}

function containerOpenComplete(){
// do what you want here when opening complete
}

function containerCloseComplete(){
// do what you want here when closing complete
}

function toggleUPSOverlay(e){
e.preventDefault();
if(!data.isAnimating){
if($els.UPSContainer.is(':hidden')){ // currently closed so open
$els.UPSContainer.show();
$els.UPSContainer.animate({
left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px',
height: data.UPSContainer.height + 'px',
width: data.UPSContainer.width + 'px'
}, 200, function(){
containerOpenComplete();
});
}else{ // currently open so close
$els.UPSContainer.animate({
left: data.windowWidth + 'px',
top: data.windowHeight + 'px',
height: 0 + 'px',
width: 0 + 'px'
}, 200,
function () {
$els.UPSContainer.hide();
containerCloseComplete();
});
}
}
}

function attachEvents(){
$els.window.on('resize', getNewWindowCorner);
$els.toggleUPSButtons.on('click', toggleUPSOverlay);
}

function initialize(){
addUPSOverlay();
getNewWindowCorner();
attachEvents();
}

initialize();
});

DEMO

center a div in center of screen with a background image using jquery

This code always works for me:

$('#yourimage').css({'top':'50%','left':'50%','margin':'-'+($('#yourimage').height() / 2)+'px 0 0 -'+($('#yourimage').width() / 2)+'px'});


Related Topics



Leave a reply



Submit