Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to center a div on the screen using jQuery?
To center a div on the screen, use the jQuery centering function jQuery.fn.center. This custom jQuery method provides flexible positioning by allowing you to center elements either relative to their parent container or to the browser window.
Example
You can try to run the following code to learn how to center a div on the screen −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
jQuery.fn.center = function(parent) {
if (parent) {
parent = this.parent();
} else {
parent = window;
}
this.css({
"position": "absolute",
"top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
"left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
});
return this;
}
$("div.myclass:nth-child(1)").center(true);
$("div.myclass:nth-child(2)").center(false);
});
</script>
<style>
div.box {
width: 300px;
height: 300px;
border: 2px solid #000000;
position: relative;
top: 10px;
left: 10px;
margin: 20px;
}
div.myclass {
width: 50px;
height: 50px;
color: white;
background: #000000;
border-radius: 4px;
text-align: center;
line-height: 25px;
font-size: 12px;
}
</style>
</head>
<body>
<div class="box">
<div class="myclass">1<br>parent</div>
<div class="myclass">2<br>window</div>
</div>
</body>
</html>
How it works
The custom center function takes a boolean parameter. When true, it centers the element relative to its parent container. When false, it centers the element relative to the browser window. The function calculates the center position using element dimensions and applies position: absolute with calculated top and left values.
This jQuery approach provides a reusable solution for centering divs dynamically, making it especially useful for modal dialogs, tooltips, and other positioned elements that need precise centering.
