CSS
Universal Centering with CSS Grid
Master how to perfectly center any element, both horizontally and vertically, within its parent container using the powerful and straightforward CSS Grid properties `place-items`.
/* HTML Structure Example: */
/*
<div class="parent-container">
<div class="centered-item">I am centered!</div>
</div>
*/
.parent-container {
display: grid;
place-items: center; /* Shorthand for align-items: center; justify-items: center; */
/* For demonstration, give the parent a fixed size */
width: 300px;
height: 200px;
border: 2px dashed #999;
background-color: #f9f9f9;
}
.centered-item {
padding: 1em;
background-color: #007bff;
color: white;
text-align: center;
}
How it works: This code demonstrates the simplest way to center any child element perfectly within its parent using CSS Grid. By setting `display: grid` on the parent container and then applying `place-items: center`, the child element will be centered both horizontally and vertically, regardless of its own size or the parent's dimensions. `place-items` is a convenient shorthand for `align-items: center` and `justify-items: center`.