jQuery

jQuery Center Div Example

Love jQuery? Need a quick way to center div in window? In this article I am going to show you how to center div using jQuery.

Example to Center Div using jQuery

In order to use this, simply apply the .center() method to your element selector and that will center the div.

<style type="text/css">
#my_div {
	background-color: #DFF2FF;
	border: 1px solid #06F;
	height: 200px;
	width: 500px;
}
.my_div_2 {
	background-color: #FFCC66;
	border: 1px solid #F90;
	height: 100px;
	width: 300px;
}
</style>

<div id="my_div">This is my_div</div>
<div class="my_div_2">This is my_div_2</div>

<script type="text/javascript">
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}

//Call the "center" function on your desired div in the following way.
//Simply replace #my_div with the ID or the class of the div that you want to center.
$('#my_div').center();
$('.my_div_2').center();
</script>

When you run the above code, you will notice that the divs are centered in the window when the page loads.

That’s it!

Do you know of any other ways to use jQuery to center div? Please share your thoughts below.

Share your thoughts, comment below now!

*

*