5k Arri Light

advertising / sales support / broadcast & web graphics / corporate & customer communications & training

CSS: Removing extra space underneath an image.

If you’ve ever tried to wrap an image in a div, you’ve surely came across the layout issue where an extra couple pixels of blank space are inserted underneath the image. Trying to get rid of this extra space has caused me to pull my hair out many times, but the fix is rather easy. All it takes is a basic understanding of the type of element that images are, and how they interact with the layout around them. First, some sample code:

  1. <div style="border: 1px solid #000;">
  2. <img src="someimage.jpg" width="270" height="184" alt="yo" />
  3. </div>

This will result in something like this:

Notice the 3 pixels of whitespace underneath the image. The reason this happens is because images are by default inline elements. Inline elements of course do not force new lines and act like text flowing along a line. The most well-known inline element is of course plain text — such as this very paragraph that you are reading now. The fonts that make up text have attributes named descenders, which are basically the part of a font that extends below the baseline on characters such as y, g, and j. Even though images aren’t like fonts and don’t have descenders, when your browser is rendering an image it treats it as an inline element and adds some space under the baseline to compensate for descenders. The easiest way to get rid of the space underneath an image is to convert it to a block element so that the browser doesn’t add extra room for descenders like so:

  1. <div style="border: 1px solid #000;">
  2. <img src="someimage.jpg" width="270" height="184" alt="yo" style="display: block;" />
  3. </div>

If for some reason you’re unable to convert your image to block mode, another way to fix it is to hard-code the height of the wrapper div to match the height of the image like so:

  1. <div style="border: 1px solid #000; height: 184px;">
  2. <img src="someimage.jpg" width="270" height="184" alt="yo" />
  3. </div>

Either of these methods will tightly and correctly wrap your image without the descender space below it like so:

  • Posted by: Chris
  • Posted on: 25/07/2013
  • Comments: 17
  • Categories: HTML, CSS,
Please let me know what you think...