Did you find this useful?
Socialize it today.


How to Center an Image of Unknown Size

Wednesday, May 15, 2013

centering

In previous articles, we covered how to center content both vertically and horizontally. However, in those examples, we knew in advance the dimensions (width and height) of the content or element we were trying to center. In this tutorial, we are going to look at a technique to vertically and horizontally center content where the width and height is unknown. There are a few techniques that can be used to accomplish this goal, but in this article, we will one of the methods that can be used using CSS and jQuery.


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.


<div id="imageContainer">
   <img id="img1" src="images/image1.png"  />
</div>


The CSS

There is very little CSS needed to style the div and image element.

#imageContent { position: relative; height:500px; background-color:#ababab; }
#img1 { position: absolute; top: 50%; left: 50%; }

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 the 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.


center image


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 elemnent using client-side jQuery.


$(document).ready(function() {
    $('#img1').load(function() {
        // Get the target image...
        var srcImg = $("#img1");
        var newImage = new Image();
        newImage.src = srcImg.attr("src");
        var imageWidth = newImage.width;
        var imageHeight = newImage.height;

        // Prepre the top and left margin values, the values need 
        // to be negative to move the image up and left within the div.
        var marginTop = -Math.abs(imageHeight / 2);
        var marginLeft = -Math.abs(imageWidth / 2);

        // Assign the new margins to the image.
        $("#img1").css( {"margin-top": marginTop + "px", "margin-left": marginLeft + "px" });
    });
});

Applying a negative margin of half the width and height will result in moving the image up and to the left as shown below...


center image vertically and horizontally


Complete Example

demo

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


<!DOCTYPE html>
<html>
<head>
<style>
  #imgContainer { position: relative; height:300px; width:300px; background-color:#ababab;}
  #img1 { position: absolute; top: 50%; left: 50%;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>

<div id="imgContainer">
   <img id="img1" src="images/image1.png"  />
</div>

<script>

    $(document).ready(function () {
        $('#img1').load(function () {
            var srcImg = $("#img1");
            var newImage = new Image();
            newImage.src = srcImg.attr("src");
            var imageWidth = newImage.width;
            var imageHeight = newImage.height;
            var marginTop = -Math.abs(imageHeight / 2);
            var marginLeft = -Math.abs(imageWidth / 2);
            $("#img1").css({ "margin-top": marginTop + "px", "margin-left": marginLeft + "px" });
        });
    });

</script>
</body>
</html>

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

CSS: The Missing Manual HTML CSS and JavaScript Editor HTML CSS: The Complete Reference