Why are formatting characters like CRLF being rendered by certain browsers as whitespace?
-
21-08-2019 - |
Question
I need someone to explain to me where this extra padding is coming from on divs that contain img elements.
You can go to http://www.dev12.com/CSSTest for live examples of my two problems.
Problem #1: Safari, Firefox and Opera render roughly 6 pixels of unwanted bottom padding on the container div. It does not matter if I explicitly set padding to 0px.
Problem #2: If I format my code so that each image is on it's own line in my html file, an additional 6 pixels of right padding are added to each image. For example, the following code block renders unwanted padding between the two images:
<div>
<span><img src="button.gif" /></span>
<span><img src="button.gif" /></span>
</div>
However, this code block does not have the unwanted space:
<div>
<span><img src="button.gif" /></span><span><img src="button.gif" /></span>
</div>
Obviously Safari, Firefox and Opera are rendering my carriage return between span tags as whitespace. I cannot recall ever having this problem before. I am writing my code in Textmate. Is there a setting I should look at to prevent this?
I always use the XHTML 1.0 Strict doctype. This is particularly confusing to me because it is so rudimentary. Somebody help me understand this!
KN
Solution
#1 That's because of the default baseline alignment of inline images - the extra space you're seeing is reserved for descenders (letters that go below the baseline: g, p, q, y, etc.) in the text surrounding your images. (The fact that you have no text is irrelevant - space for them is still reserved.)
You can get rid of it like this:
img { /* Or a suitable class, etc. */
vertical-align: bottom;
}
#2 Newlines are whitespace, and get displayed as spaces. If you had HTML like this:
<p>This is a sentence
in a paragraph.<p>
you'd expect the browser to put a space between "sentence" and "in", wouldn't you? <img>
elements are inline blocks, just like words in a paragraph.
OTHER TIPS
If I remember correctly, the HTML specs say that any and all whitespace in the source file will be rendered as a single whitespace.
For example, if you open up a new HTML doc and type
hello
world
The result will be "hello world"
The same result will appear for any of the following:
hello
world
------ or ----------
hello world
------ or ----------
hello world
Regardless how much whitespace you put between "hello" and "world" only one will render. It does not matter if the whitespace is a CRLF or a space character.