Luke Franklin
Luke Franklin

Reputation: 534

Can the HTML 'class' element attribute contain line breaks?

Can the 'class' attribute of HTML5 elements contain line breaks? Is it allowable in the specs and do browsers support it?

I ask because I have some code that dynamically inserts various classes into the element and this has created one very long line that is hard to manage. Normally I would build the class value using a variable but the CMS I'm using requires the template conditional tags to be positioned inline with the HTML. I can't use variables or PHP.

What I found in my research is that some HTML tag attributes need to be a single line, but I haven't been able to discover if the class attribute is one of those.

Does anyone know something about this?

Upvotes: 22

Views: 5140

Answers (2)

zzzzBov
zzzzBov

Reputation: 179206

Can the [class] attribute of HTML5 elements contain line breaks?

Yes. The HTML5 spec says:

The attribute, if specified, must have a value that is a set of space-separated tokens representing the various classes that the element belongs to.

The link proceeds to say:

A set of space-separated tokens is a string containing zero or more words (known as tokens) separated by one or more space characters, where words consist of any string of one or more characters, none of which are space characters.

And space characters include:

  • space (' ')
  • tab (\t)
  • line feed (\n)
  • form feed (\f)
  • carriage return (\r)

The space characters, for the purposes of this specification, are U+0020 SPACE, "tab" (U+0009), "LF" (U+000A), "FF" (U+000C), and "CR" (U+000D).

Newlines as you would add to UTF-8 documents are:

  • line feeds (\n)
  • carriage returns (\r)
  • a carriage return followed immediately by a line feed (\r\n)

Upvotes: 9

Dancrumb
Dancrumb

Reputation: 27549

Per the HTML 4 spec, the class attribute is CDATA:

User agents should interpret attribute values as follows:

o Replace character entities with characters

o Ignore line feeds

o Replace each carriage return or tab with a single space.

so you're in good shape there.

The HTML5 spec describes a class as a set of space separated tokens, where a 'space' includes newlines.

So you should be good there, too.

Upvotes: 28

Related Questions