A Beginner's Guide to CSS: Mastering Cascading Style Sheets

koustav moitrakoustav moitra
3 min read

CSS and its Syntax:

CSS stands for Cascading Style Sheets.
It controls the visual presentation (style, layout, color, fonts, spacing, etc.) of HTML elements.

Why Use CSS?

Without CSS:

<h1>Hello</h1>

With CSS:

<h1 style="color: blue; font-family: Arial;">Hello</h1>


๐Ÿ“ 3 Ways to Add CSS

MethodHow to UseExample
InlineInside the HTML tag<p style="color:red;">Text</p>
InternalInside a <style> tag in <head><style>p { color: red; }</style>
External โœ…Linked .css file<link rel="stylesheet" href="styles.css">
๐Ÿ’ก
External is the best for real projects.

CSS Syntax

selector {
  property: value;
}

โœ… Example:

h1 {
  color: blue;
  font-size: 24px;
}

This means: make all <h1> elements blue and 24px in size.


CSS Selectors

Selectors target which elements to style.

๐Ÿ”น 1. Universal Selector (*)

Targets all elements.

* {
  margin: 0;
  padding: 0;
}

๐Ÿ”น 2. Element Selector

Targets a specific HTML tag.

p {
  color: green;
}

๐Ÿ”น 3. Class Selector (.)

Targets elements with a specific class.

<p class="highlight">Hello</p>
.highlight {
  background-color: yellow;
}

๐Ÿ”น 4. ID Selector (#)

Targets an element with a unique ID.

<h1 id="main-title">Welcome</h1>
#main-title {
  font-size: 30px;
}

๐Ÿ”น 5. Group Selector

Style multiple elements at once.

h1, h2, p {
  font-family: Arial;
}

๐Ÿ”น 6. Descendant Selector

Select elements inside other elements.

article p {
  color: gray;
}

Applies to all <p> inside <article>.


๐Ÿ”น 7. Child Selector (>)

Selects direct children only.

ul > li {
  list-style-type: square;
}

๐Ÿ”น 8. Adjacent Sibling Selector (+)

Selects the next sibling only.

h2 + p {
  color: purple;
}

๐Ÿ”น 9. Attribute Selector

Targets elements by attributes:

input[type="text"] {
  border: 1px solid gray;
}

๐Ÿ”น 10. Pseudo-class Selectors

Used for states or dynamic interaction.

SelectorMeaning
:hoverWhen mouse is over element
:focusWhen an input is focused
:first-childFirst child of a parent
:last-childLast child
button:hover {
  background-color: red;
}

๐Ÿ”น 11. Pseudo-elements

Target parts of an element.

p::first-line {
  font-weight: bold;
}

Specificity (Which Style Wins?)

Selector TypeSpecificity Score
Element (p)1
Class (.x)10
ID (#id)100
Inline Style1000
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: sans-serif;
    }
    h1 {
      color: blue;
    }
    .highlight {
      background-color: yellow;
    }
    #intro {
      font-style: italic;
    }
  </style>
</head>
<body>
  <h1 id="intro">Welcome!</h1>
  <p class="highlight">This is a highlighted paragraph.</p>
</body>
</html>

0
Subscribe to my newsletter

Read articles from koustav moitra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

koustav moitra
koustav moitra