Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <style> div.box { width: 400px; height: 300px; border: 2px solid green; position: relative; top: 10px; left: 10px; } div.myclass { width: 50px; height: 50px; color: white; background: green; border-radius: 4px; text-align: center; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="box"> <div class="myclass">Box</div> </div> <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); }); </script> </body> </html>