FREELessons: 20Length: 1.2 hours

• Overview
• Transcript

# 4.1 Horizontal and Vertical Centering

One of the first things you learn when studying CSS is how to center stuff — either horizontally or vertically. In this lesson I’ll show you how you can center text and images.

## 7.Conclusion1 lesson, 01:47

### 4.1 Horizontal and Vertical Centering

One of the first things you'll learn when studying CSS is how to center stuff, either horizontally or vertically. Actually, there are three kinds of centering. One, centering lines of text. Two, a block of text or an image. And three, a block or an image vertically. So let's go over each one. First of all, I have some default styling applied here, so I have, let's see, one, two, three, four divs, each with a class of container followed by a number, and I just applied some background color padding and a margin bottom and this is what we get. So the first one, centering lines of text, let's do this container One paragraph we'll do text align center. Okay. So this will center everything inside it, really easy to remember. The second one is when you want to center a block of text or an image. So for that, let's do container number two, paragraph. And we'll start with a specified width for that paragraph. So, width, lets make it about 50%. Okay, so this is what we're looking at. And then to center it, we're gonna do margin 0 top and bottom. And auto for left and right. And that will center the whole block. So margin auto basically means the left and right margins will be calculated automatically, so they are equal. Therefore, that block is placed in the center of the container. Now, as I said, you need to specify a width. If you take this out, the paragraph will just stretch to fill the entire available width. The same thing goes for an image, so we have the third container with an image So, let's do container-3 img. And we're gonna put margin 0 auto. We don't need to specify a width here because it's an image, it already has a width. Now this doesn't work, and that's because images are inline elements by default. In order for this to work, we gotta set display to block. Save, and there it is. Now it's perfectly aligned in the middle. Now the third kind of centering is vertically. So to do that, we have this fourth container, and let's target it real quick. Container four, whoops. And we'll start by giving it a height. Let's say about fifteen ems, okay? So we can see the paragraph that will be centered. And the next thing we do is set display to table-cell. So right now, this container will behave like a table cell and that means we can apply vertical-align middle. Save. And there it is. Just remember, you need to set a height for this method to work. And there you have it, three easy methods for centering stuff in CSS.

Back to the top