December 2008

Happy new year!

It’s already 2009 (CDT), and I’d just gotten used to 2008. Happy new year, everybody.

Brilliant!

So I was just trying to figure out how to center an image inside a div with hidden overflow when the image is larger than the div, and it turns out it’s not as easy as you think. Vertical alignment is easy using vertical-align: middle. However, giving the div container text-align: center, for example, doesn’t work—the image’s left edge still aligns with the left edge of the div. After a little Googling, I found this rather ingenious solution.

<br />
&lt;style type=&quot;text/css&quot;&gt;<br />
  .centre<br />
  {<br />
    position: relative;<br />
    margin: 100px auto;<br />
    width: 200px;<br />
    height: 150px;<br />
    overflow: hidden; /* the centered bigger image&#8217;s overflow is clipped at all four sides */<br />
    background:#cfc;<br />
  }</p>
<p>  .centre span<br />
  {<br />
    position: absolute; /* makes block-box wrapped around its content */<br />
    top: 50%; /* absolute %-unit referes to the selector&#8217;s first positioned ancestor */<br />
    left: 50%; /* places the selector&#8217;s top left corner in the centre of the container div */<br />
  }</p>
<p>  .centre img<br />
  {<br />
    position: relative; /* does not move the original object, positions the image of it */<br />
    top: -50%; /* relative %-unit referes to the selector itself */<br />
    left: -50%; /* places the centre of itself in its original top left corner position */<br />
  }<br />
&lt;/style&gt;</p>
<p>&lt;div class=&quot;centre&quot;&gt;<br />
  &lt;span&gt;&lt;img src=&quot;image.jpg&quot; alt=&quot;&quot;/&gt;&lt;/span&gt;<br />
&lt;/div&gt;<br />

Follow the link to see the code snippet in its entirety, but in short what you do is that you wrap the image inside a span that is absolutely positioned at top: 50% and left: 50%, so that its top left corner is placed in the exact center of its parent, the div with the overflow. Then you relatively position the image so that its top and left are both -50%, et voilà, you have a centered image! Brilliant!