CSS Syntax and Rules
Learning Objectives
- Understand CSS rules and declaration blocks.
- Identify selectors, properties, and values.
- Write valid declarations and comments.
- Recognize common syntax errors.
Basic CSS Syntax
p {
color: red;
font-size: 18px;
margin-bottom: 12px;
}- Selector:
pidentifies paragraph elements. - Declaration block: Content inside the braces.
- Property: Such as
colororfont-size. - Value: Such as
redor18px. - Declaration: A property-value pair ending in a semicolon.
Multiple Selectors
h1, h2, h3 {
font-family: Arial, sans-serif;
}CSS Comments
/* This is a CSS comment */
p {
color: navy; /* Paragraph color */
}CSS comments begin with /* and end with */. They are ignored when the browser applies styles.
Valid and Invalid Declarations
h1 {
color: green;
font-size: 24px;
background-color: yellow;
}Incorrect property names, missing values, and invalid values can cause individual declarations to be ignored. A missing semicolon between declarations may cause subsequent text to be parsed incorrectly.
Practice
Style an h1 with a purple color, a 30px font size, and a bottom margin of 16px. Add comments describing each declaration.
Quiz
- What identifies elements in a rule? (A) Selector (B) Value (C) Comment (D) File name. Answer: A. The selector matches target elements.
- Which characters enclose a declaration block? (A) Parentheses (B) Braces (C) Square brackets (D) Quotes. Answer: B. CSS uses curly braces.
- Which punctuation separates a property from its value? (A) Comma (B) Colon (C) Period (D) Slash. Answer: B. A colon separates property and value.
- How does a declaration usually end? (A) Semicolon (B) Question mark (C) Hash (D) Ampersand. Answer: A. Semicolons separate declarations.
- Which is a CSS property? (A) blue (B) color (C) h1 (D) 20px. Answer: B. Color is a property.
- Which is a CSS value? (A) font-size (B) selector (C) 20px (D) declaration block. Answer: C. 20px is a value.
- How are CSS comments written? (A) // text (B) /* text */ (C) <!-- text --> (D) ## text. Answer: B. CSS uses slash-star delimiters.
- Can selectors be grouped? (A) Yes (B) No (C) Only with JavaScript (D) Only in HTML. Answer: A. Separate selectors with commas.
- What happens to an invalid declaration? (A) It is always repaired (B) It may be ignored (C) It deletes the page (D) It runs as JavaScript. Answer: B. Browsers generally discard invalid declarations.
- What does font-size control? (A) Text size (B) Element ID (C) URL path (D) Database size. Answer: A. It sets the size of text.
Key Takeaways
- A CSS rule contains a selector and declaration block.
- Declarations use property-value pairs.
- Comments document styles without applying them.