- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. You can try to run the following code to learn how to center a div on the screen:
Example
<!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; } div.myclass { width:50px; height:50px; color:white; background: #000000; border-radius: 4px; text-align:center; } </style> </head> <body> <div class="box"> <div class="myclass">1<br>parent</div> <div class="myclass">2<br>window</div> </div> </body> </html>
- Related Articles
- How to center a popup window on screen using JavaScript?
- How to center a window on the screen in Tkinter?
- How to duplicate a div using jQuery?
- How to center a div within another div?
- How to toggle a div visibility using jQuery?
- How to copy the content of a div into another div using jQuery?
- How to print div content using jQuery?
- How to create div dynamically using jQuery?
- How to replace innerHTML of a div using jQuery?
- How to load a page in div using jQuery?
- How to animate div width and height on mouse hover using jQuery?
- How to get the width of a div element using jQuery?
- How to get the height of a div element using jQuery?
- How to replace innerHTML of a div tag using jQuery?
- How to get innerHTML of a div tag using jQuery?

Advertisements