STP38
STP38

Reputation: 331

CSS syntax regarding extra spaces

How is it possible for CSS to recognize a space as a error?

This will work, for example: height: 50px;

But this doesn't work?: height: 50 px;

Can someone tell me why this is the case? It was really hard to find this error in my CSS.

Upvotes: 1

Views: 103

Answers (4)

TylerH
TylerH

Reputation: 21086

The W3C specification states that, for CSS Level 3, all non-zero values must be accompanied by a unit identifier, in this case px. Adding a space after the value is essentially the same as not adding a unit identifier at all. The CSS specification treats a space as an instruction that the browser should stop interpreting that property and move on to a new line or property listing.

body {
   font-size: 50 px;
}

is not okay, since the CSS is interpreted as:

What is the element? Body. Interpret according to spec if possible. There's a space; move on to the next line or property. What is the property? Font-size. This property needs a value. What is the value of the font-size property? 50. Interpret according to spec if possible. Move on to the next line or property. Next line says px;. etc. etc.

So your CSS will be interpreted by the browsers in this way. The specification allows for a space or no space between a property and a unit (size:50px; vs size: 50px;), so browsers have a use-case for either of those situations. If there is a space between a unit and a unit identifier (size:50 px;), there is no use-case for that, as it is not allowed by the spec. The browser doesn't understand what to do and moves on; the style is not applied.

Upvotes: 5

Pattle
Pattle

Reputation: 6016

height: 50 px;

Doesn't work because the browser doesn't know how to interpret it. Browsers interpret CSS according to the specification...

Just because its a space doesn't mean its okay to put it there. For example what if you did this in PHP

$var iable = 1;

Regardless of if you think its right or wrong you have to code to the specification no matter what language you are using

Upvotes: 0

Hessam
Hessam

Reputation: 1415

The value (50 in this case) and unit (px) should be next to each other withour any space in between. But the space between 50 and : is not important and is just for decorative purposes.

Upvotes: 0

krowe
krowe

Reputation: 2270

CSS doesn't really error. It either works or it doesn't. height: 50 px doesn't work because it doesn't know how to interpret 50 px.

Upvotes: 0

Related Questions