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.
See the Pen
How to horizontally center a div in a div by Joe Steinbring (@steinbring)
on CodePen.
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.
See the Pen
How to vertically center a div in a div by Joe Steinbring (@steinbring)
on CodePen.
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.
See the Pen
How to horizontally and vertically center a div in a div by Joe Steinbring (@steinbring)
on CodePen.
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.
See the Pen
How to center the text in a div centered in a div by Joe Steinbring (@steinbring)
on CodePen.
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.
[ Cover photo by Natalie Daley on Unsplash ]
The vertical centering is hard coded at 150px from the top? That works great when your parent is slightly taller than 300px.