The Objective

The objective is to center an image with an unknown width and height. To accomplish the objective, the example below will incorporate a mix of CSS and jQuery to center the image. The approach that we will take is to figure out the value of the image’s width and height client-side, then apply a top and left negative margin to offset the image’s position and have it centered vertically and horizontally.

The HTML

For this example, we only need a few lines of HTML markup. You will notice below that the image element is contained within a div element. We will use CSS styles to initially set the div’s width and height as well as the image’s top-left position.

The CSS

There is very little CSS needed to style the div and image element. At this point, we’ve placed the top, left corner of the image in the center of the div. However, we need to shift the image up and right 50% of its height and width. At this time, we do not know what either of those two values are. Here is what the image position would be within the div element. Notice the top, left corner is placed in the center of the div element.

The jQuery

This is where things get interesting. We can use jQuery to gather the width and height of the image element. Once we have that information, we will then dynamically reposition the element using client-side jQuery. Applying a negative margin of half the width and height will result in moving the image up and to the left as shown below…

Complete Example

Here is the HTML markup, CSS, and jQuery source code all put together in one file.

How to Center an Image of Unknown Size - 73How to Center an Image of Unknown Size - 81