How To in CSS
? How To Use CSS: A Quick Guide
CSS (Cascading Style Sheets) is used to style HTML elements on your webpage. Here’s how to add and use CSS effectively:
1. Add CSS to Your HTML
a) Inline CSS
Directly in an HTML tag using the style attribute.
<p style="color: blue; font-size: 16px;">Hello, world!</p>Not recommended for large projects — hard to maintain.
b) Internal CSS
Within a <style> block inside the <head> of your HTML.
<head> <style> p { color: blue; font-size: 16px; } </style></head>Good for small pages or quick testing.
c) External CSS
In a separate .css file linked to your HTML.
<head> <link rel="stylesheet" href="styles.css"></head>styles.css:
p { color: blue; font-size: 16px;}Best practice for maintainability and reusability.
2. Write CSS Rules
A CSS rule consists of:
Selector: Which element(s) to style (e.g.,
p,.class,#id)Declaration block: Inside
{}, containing property-value pairs.
selector { property: value; property2: value2;}Example:
h1 { color: red; text-align: center;}3. Use Selectors
Types of selectors include:
Element selector:
p,h1,divClass selector:
.button(elements with class="button")ID selector:
#header(element with id="header")Attribute selector:
[type="text"]Pseudo-class:
a:hover,input:focusCombinators:
div > p,ul li
4. Understand Specificity & Cascade
Inline styles > IDs > Classes > Elements
Later rules override earlier ones if they target the same element.
Use
!importantsparingly to override rules.
5. Test and Debug
Use browser dev tools (F12) to inspect elements and test CSS live.
Adjust styles and see instant results.
Example: Styling a Button
HTML:
<button class="btn-primary">Click Me</button>CSS:
.btn-primary { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer;}.btn-primary:hover { background-color: #0056b3;}