Here are a few strategies you may consider using in this scenario.
To begin with, utilizing absolute
positioning allows you to position an object relative to its parent's layout.
It is important to note that absolute
positioned elements are placed based on the subsequent parent that has absolute or relative positioning. Therefore, if the immediate parent has position: static
, it will be disregarded for the purpose of absolute positioning. This explains why, in my example, I have assigned the container div a position: relative
- to ensure the application of absolute positioning.
Secondly, the calc()
function enables derived calculations - in this instance, for precise centering, we compute the left
and right
properties as
50% of the parent's width, minus 1/2 * the desired width of the element
.
Thirdly, the z-index
property grants us authority over which element takes precedence visually.
I have promptly adjusted your work, and here is the result.
/* box_model.css */
.container {
position: relative;
height: 250px;
width: 250px;
}
.container>.target {
position:absolute;
}
.target:nth-of-type(1) {
height: 50px;
width: 50px;
background-color: red;
border-radius: 50px;
z-index: 4;
left: calc(50% - 25px);
top: calc(50% - 25px);
}
.target:nth-of-type(2) {
height: 100px;
width: 100px;
background-color: orange;
border-radius: 50px;
z-index: 3;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
.target:nth-of-type(3) {
height: 150px;
width: 150px;
background-color: yellow;
border-radius: 80px;
z-index:2;
left: calc(50% - 75px);
top: calc(50% - 75px);
}
.target:nth-of-type(4) {
height: 250px;
width: 250px;
background-color: green;
border-radius: 150px;
z-index:1;
left: calc(50% - 125px);
top: calc(50% - 125px);
}
<div class = "container">
<div class ="target"></div>
<div class ="target"></div>
<div class ="target"></div>
<div class ="target"></div>
</div>
It is advisable to refrain from manually assigning z-index values, as your application expands, unintended overlapping issues might arise.
Alternatively, you can regulate the stacking order of elements simply by their document position - such as making the largest circle the first element, rather than the last.