Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center a div

I have a problem with vertically centering a simple div. It always give margin-top="0px"

The vertical centering is the same as the horizontal centering and that works perfect.

(it is necessary to center it in javascript for further development)

Any solutions?

$(document).ready(function() {
  var width1 = $("body").width();
  var width2 = $("#main").width();
  var height1 = $("body").height();
  var height2 = $("#main").height();
  var centerw = (width1 - width2) / 2;
  var centerh = (height1 - height2) / 2;
  $("#main").css("margin-left", centerw + "px");
  $("#main").css("margin-top", centerh + "px");
});
$(window).resize(function() {
  var width1 = $("body").width();
  var width2 = $("#main").width();
  var height1 = $("body").height();
  var height2 = $("#main").height();
  var centerw = (width1 - width2) / 2;
  var centerh = (height1 - height2) / 2;
  $("#main").css("margin-left", centerw + "px");
  $("#main").css("margin-top", centerh + "px");
});
* {
  margin: 0;
  padding: 0;
  border: 0;
  float: left;
  width: 100%;
  position: relative;
  text-align: center;
  overflow: hidden;
}
#main {
  width: 400px;
  height: 600px;
  background-color: gray;
}
<body>

  <div id="main">

  </div>

</body>
like image 577
DNA Avatar asked Jun 26 '26 18:06

DNA


1 Answers

In Chrome i didn't had a problem with your code, only in firefox it doesn't work.

The problem is that the body is the same height as the box, you can set height for body as 100% or use $(window).height(); instead $("body").height();

JSFiddle

<!DOCTYPE  html>
<html>
	<head>
		<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
		<script>
			$(document).ready(function() {
			  var width1 = $(window).width();
			  var width2 = $("#main").width();
			  var height1 = $(window).height();
			  var height2 = $("#main").height();
			  var centerw = (width1 - width2) / 2;
			  var centerh = (height1 - height2) / 2;
			  console.log(width1+" " +width2 + " " + height1 + " " + height2);
			  $("#main").css("margin-left", centerw + "px");
			  $("#main").css("margin-top", centerh + "px");
			});
			$(window).resize(function() {
			  var width1 = $("body").width();
			  var width2 = $("#main").width();
			  var height1 = $("body").height();
			  var height2 = $("#main").height();
			  var centerw = (width1 - width2) / 2;
			  var centerh = (height1 - height2) / 2;
			  $("#main").css("margin-left", centerw + "px");
			  $("#main").css("margin-top", centerh + "px");
			});				
		</script>
		
		<style>			
			#main {
			  width: 400px;
			  height: 600px;
			  background-color: gray;
			}
		</style>
	</head>
	<body>
	  <div id="main"></div>
	</body>
</html>
like image 136
Artur Ziomek Avatar answered Jun 29 '26 08:06

Artur Ziomek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!