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">
<head>
    <title>Sunday Ironfoot's Image Center Problem</title>
    <link rel="stylesheet" href="Reset.css" type="text/css" />
    <style type="text/css">

        #Mosaic
        {
            position: absolute;
            top: 20px;
            right: 20px;
            bottom: 20px;
            left: 20px;
        }

        #Canvas
        {
            max-height: 100%;
            max-width: 100%;
            margin-left: auto;
            margin-right: auto;
        }

    </style>

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

</head>
<body>
    <div id="Page">
        <div id="Mosaic">
            <canvas id="Canvas" width="1600" height="1200"></canvas>
        </div>
    </div>
</body>
</html>
  • 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 over 6 years ago

1 answer

0
points

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

Answered over 6 years ago by Nathan Duran