Using jQuery to center a DIV on the screen
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:
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:
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:
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:
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:
jQueryUI - The Pro League!
For advanced playbook, jQueryUI's Position utility provides the advanced alignment and positioning. Let's put this utility to use:
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:
Fixed-positioning on scroll
Who loves it when the DIV stays centered while scrolling:3
jQuery-independent methods (Because independence is happiness)
Not a jQuery fan? Fret not! CSS3 has got your cover:
You see? That's your DIV, centered like a pro!
Was this article helpful?