HTML | Center align div inside div

1] Center a Div Vertically and Horizontally with Transform and Translate

  • First, set the position property of the parent element to relative.
  • Next, set the child element’s position property to absolute, top to 50%, and left to 50%.
  • Finally, use transform: translate(-50%, -50%) to truly center the child element:
.parent_div {
font-size: 24px;
margin: 25px;
width: 350px;
height: 200px;
outline: dashed 1px black;
/* Setup */
position: relative;
}
.child_div {
width: 50px;
height: 50px;
background-color: red;
/* Center vertically and horizontally */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

2] Center a Div Vertically and Horizontally with Flexbox

  • Flexbox is the easiest way to center an element both vertically and horizontally.
  • To center the child element(s) horizontally and vertically, apply justify-content: center and align-items: center to the parent element:
<div class="container">
<div class="child"></div>
</div>
.container {
font-family: arial;
font-size: 24px;
margin: 25px;
width: 350px;
height: 200px;
outline: dashed 1px black;
/* Center vertically and horizontally */
display: flex;
justify-content: center;
align-items: center;

}

.child {
width: 50px;
height: 50px;
background-color: red;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store