Alinging a fixed dimension div at center of webpage using css

Alinging a fixed dimension div at center of webpage using css

1 min. read

HTML markup

<!DOCTYPE html>
<html>
	<body>
		<div id="box">
			<div>I am fixed at center</div>
		</div>
	</body>
</html>

CSS rules

body
{
	padding:20px;
	font-family:Helvetica,sans-serif,arial;
}

#box div
{
	height:28px;
	border: 2px dashed #af0b0b;
	padding: 20px;

	/* Total height of this div is
	28px ( height ) + 
	2px top border width + 
	2px bottom border width + 
	20px top padding + 
	20px bottom padding 
	Total = 72px;
	*/

	color: #fff;
	font-size: 24px;
	font-weight: bold;
	text-align: center;
	text-shadow: 1px 1px 0px #960c16;
	background-color: #d21623;
}

#box
{
	width: 270px;
	padding: 10px;
	border-radius: 4px;
	background-color: #c3131f;
	box-shadow: 0px 0px 10px #ccc;
	
	/* Remove the div from normal flow to give it desired position */
	position: fixed;
	
	/* Alinging horizontally center */
	
	left: 50%;
	
	/* Total width of this div = 270px(width) + 10px left padding + 10px right padding = 290px */
	margin-left: -145px; /* Half of total width */
	
	/* Alinging vertically center */
	
	top: 50%;
	
	/* Total height of this div = 72px(height of div child of #box) + 10px top padding + 10px bottom padding = 92px */
	margin-top: -46px; /* Half of total height */
}

Computed dimensions in Google chrome developer tool

Computed dimensions in Google chrome developer tool

Conclusion from above image :

Upper spacing : -46px(margin) + 75px = 29px

Lower spacing : 0px(margin) + 29px = 29px

Upper spacing = Lower spacing => VERTICALLY CENTERED

And

Left spacing : -145px(margin) + 683px = 538px

Right spacing : 0px(margin) + 538px = 538px

Left spacing = Right spacing => HORIZONTALLY CENTERED

Write comments