Value types and grammar basics
Definition and purpose
CSS properties accept specific value types. A number has no unit, an integer is a whole number, a dimension combines a number and unit, and a percentage has a percent sign. Keywords such as auto are accepted only where the property grammar allows them.
Numbers and dimensions
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { width: 120px; opacity: .5; z-index: 2; position: relative; } </style> </head> <body> <div id="a">Sample</div> </body></html>The length resolves to 120px, opacity is a number, and z-index accepts an integer. Positioning is introduced later; here it makes the stacking value relevant.
Syntax and mental model
In a grammar, <length> | auto means either a length or the keyword auto; it is notation, not literal CSS. opacity: .5 uses a number; width: 120px uses a length; width: 50% uses a percentage. A nonzero bare number is not a width length, though zero can omit its length unit. Some property grammars accept both numbers and percentages.
Invalid value recovery
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>#a { width: 100px; width: 200; padding: 0; }</style> </head> <body> <div id="a">Sample</div> </body></html>The bare nonzero width is invalid and the earlier valid width stays. Unitless zero padding is valid.
Common mistakes
Keep the number and unit together: 12 px is not 12px. An invalid declaration is ignored, so a previous valid declaration may still apply. Opacity affects the whole rendered element, so avoid making text hard to read.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Importance and inline styles. Next lesson: Absolute and font-relative lengths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Value types and grammar basics — knowledge check
Five questions on value types and grammar basics.
Which value is a dimension?
Which is a valid nonzero width length?
What does | mean in a value grammar?
What is valid for zero padding?
What happens to width: 100px; width: 200;?