Styling Explained - CSS Rules & Best Practices
Styling in Angular
Styling means designing the UI of an application by controlling:
- Colors
- Height & width
- Layout & positioning
- Font size and appearance
- Spacing (padding, margin)
CSS stands for Cascading Style Sheets.
It is used to define how HTML elements should look on the screen.
Types of Styling in Angular
Angular supports multiple ways to apply styles:
Component Styles
Global Styles
Inline Styles
Internal Styles
External Styles
Multiple CSS files per component
Each approach has a specific use case.
Component Styles
What Are Component Styles?
- Styles written inside a component’s
.cssfile - Example:
app.component.css,user-data.component.css - Styles apply only to that component
Example
Key Points
- Component styles do not affect other components
- Best for component-specific UI
- Angular uses style encapsulation by default
Global Styles
What Are Global Styles?
- Styles written in
styles.css - Apply to the entire application
- Affect all components
When to Use Global Styles?
- Common headings
- Buttons
- Typography
- Theme styles
- Reusable UI elements
Example
Applies to all components
Breaks isolation if overused
Styling Multiple Components (Common Scenario)
Problem
Same style repeated in:
app.component.cssuser-data.component.cssadmin-data.component.css
Code duplication
Hard to maintain
Solution
Move common styles to styles.css
Clean
Reusable
Scalable
Creating Multiple Global CSS Files
Example Use Cases
buttons.cssthemes.csscommon.css
Steps to Use Extra Global CSS Files
- Create CSS file inside
src - Register it in
angular.json
Restart the server after changes
Button Styling (Real-world Example)
Base Button
Button Variants
Usage
✔ Bootstrap-like structure
✔ Scalable styling system
Inline Styles
What Are Inline Styles?
- Written directly inside HTML
Use Case
- Very small, one-time styling
- Quick debugging
Not recommended for large apps
Internal Styles
What Are Internal Styles?
- Written inside
<style>tag
Not recommended in Angular
Component CSS is better
Inline Template & Styles (Small Components)
When Component Is Very Small
You can write HTML & CSS directly in .ts file.
Useful for small components
Avoid for large layouts
Loading Multiple CSS Files in One Component
Default
Multiple Files
Helps organize styles
Keeps code clean
Important Styling Rules (Best Practices)
Use component styles for component-specific UI
Use global styles for reusable elements
Avoid repeating CSS
Separate large styles into multiple files
Follow naming conventions (btn-primary, btn-warning)
Avoid inline styles for large applications