Sub topic 1
How HTML and CSS Work Together
Prerequisites
Assume you know basic HTML elements such as html, head, body, and p. You should also be able to edit a text file, open an HTML file in a browser, and understand a relative file path.
HTML defines a document's structure and meaning. CSS, or Cascading Style Sheets, defines how that structure is presented. The browser parses the HTML into elements, matches CSS rules to those elements, and then calculates the layout and appearance.
Keeping structure in HTML and presentation in CSS makes a page easier to change. For example, changing a color in CSS can update many paragraphs without editing each paragraph.
Anatomy of a CSS Rule
A CSS rule contains a selector and a declaration block. A selector identifies the elements to style. A declaration contains a property and a value.
p {
color: darkblue;
line-height: 1.5;
}Here, p is the selector. color and line-height are properties. darkblue and 1.5 are their values. Each property-value pair ends with a semicolon. The declarations apply to every p element matched by this rule.
Inline Styles: the `style` Attribute
An inline style is a CSS declaration written in an element's style attribute:
<p style="color: crimson; font-weight: bold;">
This paragraph is styled inline.
</p>The browser applies these declarations only to this p element. Inline styles can be useful when a value is generated for one specific element or when testing a quick change. They become difficult to maintain when many elements contain repeated style attributes.
When several declarations target the same property, the browser uses the CSS cascade. It considers factors such as where a declaration came from, selector specificity, and source order. Inline declarations usually take precedence over ordinary rules from a stylesheet.
Exercise
What color will this paragraph use, and why? <p style="color: red;">Text</p> when a stylesheet contains p { color: blue; }
Show answer
It will use red because the inline declaration has higher precedence than the ordinary p rule.