CSS
🎨 Basic CSS Rules and Important Guidelines
When writing CSS, there are some fundamental rules and best practices you should always follow. These rules help you write clean, efficient, and maintainable code.:
Let’s go step by step 👇
🧩 1. Use the <style> Tag for Internal CSS
If you write CSS directly inside your HTML file, it must be placed inside the <style> tag (usually in the <head> section).
Example:
<head>
<style>
p {
color: blue;
}
</style>
</head>
💡 Tip: This method is called Internal CSS and is best for small projects.
🧩 2. Always Use Curly Braces { }
Every CSS rule must be written inside curly braces { }.
Example:
h1 {
color: red;
font-size: 24px;
}
💡 Explanation: The selector (h1) defines what to style, and the code inside { } defines how to style it.
🧩 3. Use the style Attribute for Inline CSS
Example:
<p style="color: green; font-size: 18px;">
This paragraph is green.
</p>
⚠️ Note: Inline CSS should only be used for quick or temporary styling.
🧩 4. Use Classes for Reusable Styles
If you want to apply the same style to multiple elements, use a CSS class.
Example:
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
<p class="highlight">This text is highlighted.</p>
<p class="highlight">This one uses the same class.</p>
💡 Tip: Classes help you write reusable and organized CSS.
🧩 5. Separate Property and Value with :
In CSS, a colon : separates the property from its value.
Example:
p {
color: red; /* property : value */
}
🧩 6. End Each Rule with ;
Each CSS property should end with a semicolon ;.
Example:
p {
color: red;
font-size: 18px;
}
💡 Best Practice: Always use ; even if it’s the last rule.
🧩 7. Use Commas , for Multiple Selectors
To apply the same styles to multiple elements, separate selectors with commas.
Example:
h1, h2, h3 {
color: purple;
text-align: center;
}
💡 Result: All headings (h1, h2, h3) will share the same style.
🧩 8. Link External CSS Correctly
To use an external CSS file, link it using the <link> tag inside <head>.
Example:
📘 HTML:
<link rel="stylesheet" href="style.css">
📘 style.css:
body {
background-color: #f5f5f5;
}
⚠️ Important: Never use <style> tags inside a .css file.
💡 Summary
- Use
<style>for internal CSS - Use { } for every CSS rule
- Use : to separate property and value
- Use ; to end each rule
- Use classes for reusable styles
- Use external CSS for real projects
