Tabla de contenidos
Con las propiedades left: 0, top: 0, right: 0, bottom: 0 y margin: auto
<div class="container">
<div class="item-container"></div>
</div>
.container {
position: relative;
background-color: red;
width: 100px;
height: 100px;
.item-container {
position: absolute;
inset: 0; /*top, right, bottom, left*/
margin: auto;
width: 50%;
height: 50%;
background-color: teal;
}
}
La propiedad de CSS inset define el bloque lógico que nos permite prescindir de left: 0, top: 0, right: 0, bottom: 0 y margin: auto.
See the Pen Centering with position by webFerrol (@webferrol-the-typescripter) on CodePen.
Con flex también podemos centrar los elementos hijos
.flex-container {
display: flex;
justify-content: center;
align-items: center;
}
Con grid también podemos centrar los elementos hijos
.grid-container {
display: grid;
place-items: center;
}