How CSS Works
CSS works by selecting HTML elements and applying styles to them. The browser reads the HTML, builds a structure called the DOM (Document Object Model), and then applies the styles from CSS to render the page visually.
1. The Browser Rendering Process
When a web page loads, the browser goes through several steps:
- HTML is parsed to build the DOM (Document Object Model)
- CSS is parsed to build the CSSOM (CSS Object Model)
- Both models are combined into a render tree
- The render tree is used to paint elements on the screen
2. CSS Selectors and Rules
CSS uses selectors to target HTML elements, and applies rules (properties and values) to style them.
p {
color: red;
font-size: 18px;
}
In this example, all <p>
elements will appear in red with font size 18px.
3. Cascading and Specificity
The "Cascading" in CSS means that styles can come from multiple sources, and the most specific one takes priority. Style rules are applied based on:
- Importance (e.g.,
!important
) - Specificity (e.g., ID > class > element)
- Source order (the last rule overrides earlier ones)
4. Inheritance
Some CSS properties (like font and color) are inherited from parent elements by default. Others (like padding or border) are not.
You can control inheritance using the inherit
, initial
, or unset
keywords.
5. Applying CSS to HTML
CSS can be applied in three main ways:
- Inline: directly within the HTML element
- Internal: inside a
<style>
tag in the<head>
- External: linked via a separate
.css
file
Conclusion
CSS works by defining rules that are applied to HTML elements through the browserβs rendering engine. Understanding how CSS is parsed, cascades, and is inherited is essential to mastering layout and design in web development.