Here is a method you could try:
div.father {
margin: 0 auto;
width:300px;
height:300px;
border:1px solid black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
div.son {
margin: 0 auto;
width:100px;
height:100px;
border:1px solid black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="father">
<div class="son"></div>
</div>
Using position: absolute
will position both the son and father elements outside of the standard flow. By utilizing top
and left
, you can specify the exact offset from the relative parent element with a position of absolute/relative/fixed
or <body>
. Additionally, using transform: translate(-50% -50%)
allows for centering the element based on its center point rather than top-left corner.
It's important to note that for older browser versions, you may need to include prefixes like -moz-
, -o-
, -webkit-
, and -ms-
before the transform
property.
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
If compatibility with all versions of Internet Explorer is necessary, using a polyfill for flex
instead may be a better option.