7 days of unlimited WordPress themes, plugins & graphics - for free!* Unlimited asset downloads! Start 7-Day Free Trial
FREELessons: 20Length: 1.2 hours

Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

4.2 Absolutely Center an Image

Absolutely centering an image basically means putting that image in the middle of its parent element. This can be used in a variety of situations, for example: displaying a zoom in icon in the middle of a blog post image.

There are actually two methods of doing this, let’s take a look at each one.

4.2 Absolutely Center an Image

Absolutely centering an image, basically means putting that image in the middle of its parent element. This can be used in a variety of situations, for example, displaying the zoom in icon in the middle of a blog post image. There are actually two methods of doing this. So let's take a look at each one. First of all, let me show you the setup I have here. So we have a basic, we have a first div, with a class of image-container-1, which is blank. And then a secondary div which contains a 200 by 200 image. In CSS, I just applied a background color and a margin to both containers. So the first method involves background images. So let's do image-container-1. Okay, I'm going to set, first of all, a width of 100%, just to make it span on the entire width. And then I'm gonna set a min-height, a minimum height, let's do about 30 m's. Okay, let's have a look. Okay, so that is our first container. And then, I'm gonna do background, let's do color. And then url, and I'm going to do http the path to the image we want to show. I'm going to put it center, center, and this is the most important part, and no-repeat. And there it is. That is an image positioned right in the center of our container. And that's because we set the background image at center center. If I change this to left, that's gonna be put on the left side. All right, so that is the first method, really, really simple. Now the second method involves absolute positioning of an image. So, I'm gonna do image-container-2. I'm gonna start with position, relative, and also let's add a minimum height of 30 ms. image-container-2 img, start with this position, absolute, and then set the top to 50% and left to 50%. Save, and as you can see, the top left corner is positioned in the center of its parent. So we gotta shift this to the left and to the top by half its width and height. So the easiest way to do that is to set margin-top minus half its height. And that is 100 pixels. Same goes for margin left, minus half of its width. Save, and there it is, positioned perfectly in the center. Now just remember you're not limited to images here. You can absolutely center any kind of html element by using the second method of course, as long as that element has a width, a height, and is capable of receiving margins.

Back to the top