How to center the two squares inscribed in the largest square with CSS?

Posted on

Question :

I would like to leave the three squares of the code below, centered symmetrically in relation to the center of the largest square that has the black background.

	height: 100px;
	width:  100px;
	background: pink;
	margin:0 auto;
	padding: 20px 20px 20px 20px; 
    height: 200px;
	width:  200px;
	background: red;
	margin: 0 auto;
	padding: 20px 20px 20px 20px; 
    height: 300px;
	width:  300px;
	background: black;
	margin: 0 auto;
	padding: 20px 20px 20px 20px; 
<div class="box3">
	<div class="box2">				
	       <div class="box">

You’re also on the jsfiddle .

Answer :

Just set the margin property in the CSS of the inner squares. Using percentage you can calculate the distance you want to give at each end. In the case of margin: 10% auto; , I am saying that the top and bottom margins will have 10% of the size of the div that contains it, and that the right and left margins will automatically be the same size.

Remember that the order of the margins in the margin property are: top, right, bottom, left. By specifying only one value, all margins will be the same size; two values the margins will be mirrored; three and four follow the original rule: top, right, bottom, left.

See the behavior in jsfiddle .


Leave a Reply

Your email address will not be published. Required fields are marked *