Explain Codes LogoExplain Codes Logo

Using jQuery to center a DIV on the screen

javascript
responsive-design
promises
callbacks
Nikita BarsukovbyNikita Barsukov·Mar 9, 2025
TLDR

To center a DIV on the screen using jQuery, assign position: fixed and compute top and left values by subtracting half of the DIV's dimensions from half of the window's dimensions, which is done using the transform: translate(-50%, -50%) property:

$(window).on('load resize', function() { var $div = $('#yourDivId'); $div.css({ 'position': 'fixed', 'left': '50%', 'top': '50%', 'transform': 'translate(-50%, -50%)' }); });

This method centers it every time the page loads or the window resizes. Remember to replace #yourDivId with your actual div identifier.

Let's handle the real world (Read: Window resize and scroll offset)

Adapting to window resize

Not everyone's screen is a 24-inch beauty. Therefore, continuously aligning your DIV with window resizing to keep it fitting perfectly is a task. Here is how you can tackle that:

$(window).resize(function() { centerDiv(); }).resize(); // Because first impressions matter. function centerDiv() { var $div = $('#yourDivId'); // That's your DIV, duh! $div.css({ 'position': 'fixed', 'left': '50%', 'top': '50%', 'transform': 'translate(-50%, -50%)' }); }

Keeping head high while scrolling

Let's make sure the div remains in the limelight despite the scrolling. Consider the calculations taking into account the scroll offset:

$(window).on('load scroll resize', function() { var $div = $('#yourDivId'); // Yeah, it's still your DIV! var windowWidth = $(window).width(); var windowHeight = $(window).height(); var divWidth = $div.outerWidth(); var divHeight = $div.outerHeight(); var leftPosition = Math.max((windowWidth - divWidth) / 2 + $(window).scrollLeft(), 0); var topPosition = Math.max((windowHeight - divHeight) / 2 + $(window).scrollTop(), 0); // Math.max? Because your DIV ain't a trekker; negative offsets are a big NO! $div.css({ 'position': 'absolute', 'left': leftPosition, 'top': topPosition }); });

Universal attraction (via a plugin)

Roulette time: Every time you visit the page, the DIV is still at the center. Code reusability is a programmer's best friend. And our buddy here is jQuery plugin:

$.fn.center = function () { this.css("position","fixed"); 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; } $('#yourDivId').center(); // And voila! Your DIV is like the Earth. Centered.

Responsive and dynamic scenarios

Fluid dimensions

Screens come in all shapes and sizes. So, we set percentage-based widths in our CSS, for the <div> to fit in every screen perfectly:

#yourDivId { width: 50%; /* Adjust as per your requirement */ height: auto; /* Maintains aspect ratio */ }

jQueryUI - The Pro League!

For advanced playbook, jQueryUI's Position utility provides the advanced alignment and positioning. Let's put this utility to use:

$("#yourDivId").position({ my: "center", at: "center", of: window // Because centering is all about the window! });

Handling edge cases and concerns

Negativity? Not here!

When the window is narrower than your DIV, (window size - div size) / 2 can sadly be negative. Using Math.max enables us to ensure the positive attitude of our positioning:

left: Math.max(0, (windowWidth - divWidth) / 2), top: Math.max(0, (windowHeight - divHeight) / 2)

Fixed-positioning on scroll

Who loves it when the DIV stays centered while scrolling:3

#yourDivId { position: fixed; // Stay right where you are! top: 50%; left: 50%; transform: translate(-50%, -50%); }

jQuery-independent methods (Because independence is happiness)

Not a jQuery fan? Fret not! CSS3 has got your cover:

#yourDivId { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); }

You see? That's your DIV, centered like a pro!