I want <code>
tags to behave like <pre>
tags. But the problem is that I get a line break at the beginning of the block. How do I get rid of that line break?
This shows what I mean ...
http://jsfiddle.net/6NmPN/
This appears to be a browser bug. See e.g. this page. SGML (and thus HTML) says that the browser needs to remove a newline immediately following an opening tag, or immediately preceding a closing tag. But it appears that most browsers (note: not all) only adhere to this requirement on the <pre>
tag and not on other tags such as the <code>
tag.
So, it appears there's not much you can do about it. The only possible fix I can think of is using XHTML strict. That's XML, not SGML. Perhaps browsers will treat all elements equally then. I'm not sure, it's just an idea.
Just to be clear, this is not a browser bug. The HTML5 specification says this for the pre element
In the HTML syntax, a leading newline character immediately following the pre element start tag is stripped.
and in the tree construction stage of the parser, for the in body mode:
A start tag whose tag name is one of: "pre", "listing"
...
Insert an HTML element for the token.
If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)
...
As others have said, there's no way of emulating this behaviour with CSS. You could, of course, remove any initial line feeds of <code>
elements with JavaScript.
Note that this says, "In the HTML syntax ..."
. This would not happen if the page was XHTML-conformant and it was served with an XML content type. e.g. application/xhtml+xml. In that mode, both pre
and code
would have the extra line at the start. However, this is not supported in IE versions prior to IE9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With