Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Doctype screws up DIV heights?

Tags:

html

css

When rendering a page in Chrome, Safari, or Firefox on Mac, if I use the HTML5 doctype

<!DOCTYPE html>

and put an image inside a div, the div is rendered consistently 4 pixels too tall. If I use the older doctype

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

The divs are rendered correctly, which is the same height as the image inside it. This is using the exact same HTML and CSS code. The only thing that changes is the doctype and an extra 4 pixels show up. Is there any way to fix this?

like image 698
Jarrod Ballou Avatar asked Jul 14 '11 21:07

Jarrod Ballou


2 Answers

http://hsivonen.iki.fi/doctype/

<!DOCTYPE html> = Standards Mode - http://jsbin.com/ogacor

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> = Almost Standards Mode - http://jsbin.com/ogacor/2

To fix it, add display: block or vertical-align: top (or bottom) to the img.

The reason this happens in the first place is that imgs are by default inline elements, and have a default vertical-align of baseline. The baseline does not touch the bottom of the containing element - the gap is the distance between the two.

See:

  • https://developer.mozilla.org/en/Gecko%27s_Almost_Standards_Mode
  • https://developer.mozilla.org/en/Images%2c_Tables%2c_and_Mysterious_Gaps
like image 120
thirtydot Avatar answered Sep 20 '22 02:09

thirtydot


HTML5 specifies that the whitespace within elements should be rendered. Therefor you get the 4px extra, if you set font-size to those elements to 0 for example, the space will dissapear.

like image 41
Johan Avatar answered Sep 21 '22 02:09

Johan