Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can an image of unknown size be centered within a div of known size?
    primarykey
    data
    text
    <p>I'm trying to centre an image of unknown size within a div of known size, such that the image is centered both vertically and horizontally within the div and the aspect ratio of the image is not distorted.</p> <p>Here's an <a href="http://tinyurl.com/27p85bh" rel="nofollow">example</a></p> <p>This code almost does the job but both images look shifted down slightly... by maybe a couple of pixels. Why?</p> <p>The HTML;</p> <pre><code>&lt;body&gt; &lt;div class="container" id="c1"&gt; &lt;img src="test.jpg"/&gt; &lt;/div&gt; &lt;div class="container" id="c2"&gt; &lt;img src="test.jpg"/&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>The CSS;</p> <pre><code>.container { text-align: center; /* Center the image horizontally */ margin: 1em; /* Just for looks */ background: red; /* Just for looks */ } .container img { vertical-align: middle; /* See note below */ max-height: 100%; /* Limit the image size to fit the container */ max-width: 100%; /* Limit the image size to fit the container */ } #c1 { width: 8em; height: 4em; /* See note below */ line-height: 4em; /* See note below */ } #c2 { width: 5em; height: 7em; /* See note below */ line-height: 7em; /* See note below */ } </code></pre> <p>Note: The image is vertically centered within the container by making the line-height of the container the same as the height of the container, and applying {vertical-align: middle;} to the image. This should vertically center the image within the container and it almost works, except that the image is always two pixels too low.</p> <p>I've tried doing * {margin:0; padding:0} and several reset.css files but still the image appears to be shifted down a bit.</p> <p>So my question is really two questions;</p> <ol> <li>How can an image of unknown size be centered within a div of known size?</li> <li>Why is there a small gap between the img and the edge of the div?</li> </ol> <p>Regards, a CSS newbie.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload