In this week’s blog post, I want to cover how to center divs inside of other divs horitontally, vertically, and both horizontally and vertically. You can do this with CSS Grid or Flexbox but I want to go over how to do it with standard CSS.
Let’s start with how to horizontally center a div in a div.
For this one, our parent div is set to 100% of the width of the screen and the child div is set to 50% of the screen. We then set the margin of the child div to auto. By setting the left and right margins of an element to auto, we have them take up the available horizontal space in the element’s container equally. This will work for horizontal margins only. When we get to the next bit, this technique won’t help us.
Next, let’s cover how to vertically center a div in a div.
For this one, our child div is set to an absolute position, which positions it relative to the nearest positioned ancestor (the parent). We are also using a top property, which specifies the distance between the outer edge of the top margin and the inner border of the parent. The value for the top property is 50% of the height of the parent, to give us a vertical alignment.
The next natural step is to show how to both horizontally and vertically center a div in a div.
This builds upon the previous example but adds the use of a left property and a width property. By setting the left property to 33% and the width property to 33%, the right side will also be 33% (or technically 33.9%, but whatever). That centers the div horizontally.
The one remaining thing is to center is the content that lives in the child div.
This part is pretty simple because we only need our old friend
text-align: center;, that makes it so that the inline contents are centered within the line box.
Have any question, comments, etc? Feel free to drop a comment, below.