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:
- Length can be “auto”
- Has a floating point number with an optional + or – sign.
- 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.
- Percentage cannot be negative.
- 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:
Explanation of the above expression:
- 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.
- 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.
- 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
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:
Another example of the RegEx with point 1 and point 3 as optional:
PS: As Sudipto Choudhury (our “Regular Expressions Knight”) says, “It is always good to really know your Regular Expressions than using them blindly.”