While working on my project I’ve found out that \n in html source is displayed as space between these 2 lines in browsers. For example,
a
b
in browsers is displayed as a b. How can I avoid this “space” without removing line-break? The result I want is ab right next to each other — not on separate lines, not with a space between them.
I generate quite big form on fly using php, for readability, I use PHP_EOL that is the same as \n, but in browsers appears extra white-spaces. I want to get rid of them.
Updated answer:
In the comments below you’ve said that the result you’re looking for is “ab” right next to each other, with no space or line break at all between them.
If “a” and “b” are really text, I don’t believe you have any option, you have to remove the linebreak if you want them next to each other. (I realize you said you didn’t want to do that, I’m just saying, I don’t think you have a choice.)
If “a” and “b” are elements (you’ve said you’re outputting a big form), you can play games with negative CSS margins, but it gets ugly fast. Or the old trick of moving that line break into a tag, e.g.:
The line break within the tag is not displayed (because it’s in a tag, not text).
The link below on inter-element whitespace may also help, depending on your overall markup; basically there are times the browser will disregard whitespace between elements, so you might be able to adjust things slightly to make it do that.
You’ve said you’re using it for readability. I suppose another option, although it’s really verbose, is to put the line break in a comment:
…but again, quite verbose (and probably not doing much for readability).
Your best bet is what you said you don’t want: Remove the linebreak. 🙂
Original answer:
(From when it was unclear that you wanted “ab” right next to each other; just about everyone thought you wanted to have the line break shown.)
Because the HTML standard says that all sequences of whitespace characters (other than inter-element whitespace) are treated as a single space. So for HTML, a newline, space, tab, carriage return, and formfeed are all exactly equal: They’re displayed as a space.
There are a few ways:
You can use a
brelement:You can put
aandbin separate containers that use block display (bothpanddivdo by default, and you can use CSS to applydisplay: blockto others).or
etc
If you really want that newline to be treated as a line break, you can use a
preelement, which has special handling of pre-formatted text…and you can apply that same sort of handling to other elements using CSS’s
white-spacestyle (valuespre,pre-wrap, andpre-line).