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

Asked

Viewed 1,301 times

3

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.

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

Also in the jsfiddle .

1 answer

1


Just set the property margin in the CSS of the internal squares. Using percentage it is possible to calculate the distance you want to give at each end. In the case of margin: 10% auto;, I’m saying the upper and lower margins will be 10% the size of the div that contains it, and that the right and left margins will automatically be the same size.

It is worth remembering that the order of the margins in the property margin are: upper, right, lower, left. Specifying only one value all margins will have the same size; two values the margins will be mirrored; three and four follow the original rule: top, right, bottom, left.

See the behavior on jsfiddle .

  • Thanks man!! Great help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.