I want to place an Image on the absolute center of the browser window, or more specifically a <canvas> element with an image loaded in it. Whats more I want that image to remain at the center no matter what browser resolution is applied, and even as the browser window is resized, while also maintaining the image's aspect ratio. One more caveat, the image's dimensions and aspect ratio won't be known in advanced.

I've so far got the image to center horizontally but not vertically, you can see what I have so far here http://www.dominicpettifer.co.uk/Files/ImageCenter/Test.html If you resize your browser window you'll see that the image is dynamically resized and horizontal aligned, except if you resize you browser to the narrow column the image appears at the top. I have looked at various examples online of vertical centering but none of them seem to work with my example, they seem to assume a fixed height.

Note: I'm building an HTML5 app, so it doesn't need to work on any version of IE, and can use CSS3 properties if neccessary. I could probably write some JavaScript that could do this, but wanted to see if there was a pure CSS3 solution first.

Here's the the HTML:

<!DOCTYPE html>
<html lang="en">
    <title>Sunday Ironfoot's Image Center Problem</title>
    <link rel="stylesheet" href="Reset.css" type="text/css" />
    <style type="text/css">

            position: absolute;
            top: 20px;
            right: 20px;
            bottom: 20px;
            left: 20px;

            max-height: 100%;
            max-width: 100%;
            margin-left: auto;
            margin-right: auto;


    <script type="text/javascript">
        // JavaScript to load in Canvas image (snip)

    <div id="Page">
        <div id="Mosaic">
            <canvas id="Canvas" width="1600" height="1200"></canvas>
  • I've just noticed this doesn't seem to work properly in Chrome, it doesn't seem to keep the aspect ratio intact like Firefox does. Might need to use JavaScript solution after all. Sunday Ironfoot almost 7 years ago

1 answer


The only way to do this without JavaScript is to use a table.

Answered almost 7 years ago by Nathan Duran