Regular Expression To Validate CSS Length and Position Values

In CSS, length and position of various elements are provided as decimal numbers. Width, height, margin, padding, border-thickness, etc are some example CSS attributes where we need to specify a length.

A valid CSS length value follows a set rules:

  1. Length can be β€œauto”
  2. Has a floating point number with an optional + or – sign.
  3. The floating point number has a trailing length unit ((The valid CSS length units are:  absolute (in, cm, mm, pt, pc) units and  relative (em, ex, px) units. For more information on CSS length units, see MSDN Library: http://msdn.microsoft.com/en-us/library/ms531211(VS.85).aspx)) or percentage.
  4. Percentage cannot be negative.
  5. 0 can be specified as length and without unit

The above can be validated using Regular Expressions in very simple steps.

A comprehensive RegEx to validate the CSS length value would be:

^(auto|0)$|^[+-]?[0-9]+.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)$

Explanation of the above expression:

^(auto|0)$
indicates that the string can be exactly “auto” or “0”
^[+-]?
allows for the value to optionally begin with a plus or minus sign. A caret (^) sign before any regular expression specifies that the expression should match the beginning of a string.
[0-9]+.?([0-9]+)?
represents a floating point number with optional decimal. A question mark after any literal marks that expression as optional. Here .? denotes an optional decimal point and even the figures following this is optional.
(px|em|ex|%|in|cn|mm|pt|pc)$
signifies that the value should end with either of the nine possible units. A $ at the end of an expression indicates that the expression should match the end of the string.

Note:To effectively use this Regular Expression on a single string or single value, use the
iand gmodifiers to make the parsing case insensitive and global.

Other variants of the CSS length validator Regular Expression:

A RegEx without considering point 1 (auto) will simply be:

^[+-]?[0-9]+.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)$

Another example of the RegEx with point 1 and point 3 as optional:

^[+-]?[0-9]+.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)?$

PS: As Sudipto Choudhury (our “Regular Expressions Knight”) says, “It is always good to really know your Regular Expressions than using them blindly.”

8 Replies to “Regular Expression To Validate CSS Length and Position Values”

    1. The section of the regex 0-9]+.?([0-9]+)? has a question-mark at the end of it, indicating that post decimal point number is optional. Thus “5.px” is valid!

      Also 0 and any other unit-less number is marked as valid by this regex. I prefer this because many older CSS implementations have unit-less values where default unit is browser specific.

  1. This is not correct, i think the correct regexp is

    /^auto$|^[+-]?[0-9]+.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)?$/ig

    while in the example you had two backlsashes πŸ™‚

Leave a Reply to JD Bell Cancel reply