MynaG's Bits n Bytes

28 Nov, 2012

Solved – Remove space below an image in DIV when vertically aligned in HTML

Posted by: mynag In: Solution & tips|Web developing/Coding

Problem

There are times when you may need to vertically align images on top of one another and the way to do it is to place the images in the <DIV> tag. That’s when you begin to find an annoying white space just below the images with a height of about 5  pixels. You have set all paddings and margins to ZERO and the mysterious space still persistently appear below the images.

Below is an example of how it might appear. As seen here, I have set the background color to blue to make obvious the spacing between these 2 vertically stacked images.

The html code to create the above is shown below:

<head>
<style type=”text/css”>
.imgclass
{
background-color:#1122CC;
text-align:center;
}
</style>
</head>

<body>

<div class=”imgclass”>
<img src=”koala.jpg”>
</div>
<div>
<img src=”flower.jpg”>

</div>
</body>
</html>

 

Solution

Check the very first line of the HTML document and make sure you have the <!DOCTYPE> declaration stated.
Different DOCTYPE declaration can give different results. HTML 5 <!DOCTYPE html> may give a spacing if you did not include img{ display:block; }.

Refer to the W3schools for Common DOCTYPE declarations.

XHTML 1.0 Transitional for instance will not result in a space below the image.
Place it’s DOCTYPE declaration at the top of the page or replace and existing DOCTYPE.

For example:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

 

Update your HTML code and refresh the page. (Make sure that your cache is cleared)

And Viola! The space between the 2 vertically aligned images disappear! See the below example.

no space below vertically aligned images in div

Recommended solution

Some DOCTYPE will still result in a spacing below the image and that include XHTML 1.0 Strict, HTML 4.01 Strict and the latest HTML 5 .  HTML 5 has some enhanced features which actually make writing HTML codes easier than the earlier version.  And in any case, if you are working on a Tumblr theme template, you have no other option but to work on your page with HTML 5 because Tumblr will update your page to HTML 5 even if you have it declare as other DOCTYPE. So the following solution will surely get rid of the space no matter which DOCTYPE you use.

Simply specify “display:block” in an img class in your stylesheet.

img
{
display:block;
}

Similarly, you should now have the space removed as well.

Tags: , ,

No Responses to "Solved – Remove space below an image in DIV when vertically aligned in HTML"

Comment Form

Categories

About

Welcome to MynaG's Bits and Bytes. My little journal containing bits and bytes of the internet, web programming and etcetera