Centering

To center a block within its parent, equal left and right margins should be set:

 

#myDiv {margin:1em 8em; }

 

If a specific width is required, the individual margins should be set to auto:

 

#myDiv {margin-left:auto; margin-right:auto; width:300px;}

 

<!DOCTYPE html>
<html>
	<head>
		<title>My Document Title</title>
	</head>
	<body>
		<div style="margin: 1em 18em; border:solid 1px red;">
			<p>But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness.</p>
		</div>
		<br>
		<div style="margin-left:auto; margin-right:auto; width:300px; border:solid 1px green;">
			<p>No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful.</p>
		</div>
	</body>
</html>

Save & refresh browser:

iframe source*

Leave a Reply