Master CSS Basics: Write Your First Stylesheet (Part 1)

This tutorial walks beginners through CSS fundamentals, covering what CSS is, how to include styles, basic syntax, selector types, cascade and specificity, the box model, units, background, borders, display, positioning, overflow, and a complete card component example, with practical tips for each topic.

CodeNotes
CodeNotes
CodeNotes
Master CSS Basics: Write Your First Stylesheet (Part 1)

1. What Is CSS?

CSS (Cascading Style Sheets) describes the appearance and layout of HTML documents. Think of HTML as the house skeleton and CSS as the interior design—colors, furniture placement, lighting.

<!-- No CSS world -->
<p>This is plain text</p>

<!-- With CSS -->
<p style="color:#0052d9; font-size:18px; font-weight:bold;">This text becomes blue, bold, 18px</p>

2. Three Ways to Include CSS

1. Inline Styles (Not Recommended)

<h1 style="color:red; font-size:24px;">Title</h1>

Drawback: mixes style with structure, making maintenance hard.

2. Internal Style Sheet

<head>
  <style>
    h1 { color:red; font-size:24px; }
  </style>
</head>

3. External Style Sheet (Recommended)

<head>
  <link rel="stylesheet" href="styles.css" />
</head>

/* styles.css */
 h1 { color:red; font-size:24px; }

External files can be reused across multiple pages, making them the most common practice in projects.

3. Basic CSS Syntax

selector {
  property: value;
  property: value;
}

Example to turn all paragraphs gray with a line‑height of 1.8:

p {
  color:#666;
  line-height:1.8;
}

Property name and value are separated by a :.

Each declaration ends with a ;.

Comments use /* */.

4. Selector System

Selectors determine which elements a rule applies to, forming the core power of CSS.

4.1 Basic Selectors

div {}

– tag selector matches all div elements. .btn {} – class selector matches elements whose class includes btn. #header {} – ID selector matches the element with id="header". * {} – universal selector matches every element.

/* Tag selector */
button { cursor:pointer; }

/* Class selector (most common) */
.card { border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.1); }

/* ID selector (unique, use sparingly) */
#app { max-width:1200px; margin:0 auto; }

4.2 Combinator Selectors

/* Descendant selector */
.nav a { text-decoration:none; }

/* Child selector */
.nav > a { color:#333; }

/* Adjacent sibling */
h2 + p { margin-top:0; }

/* General sibling */
h2 ~ p { color:#666; }

/* Grouping */
h1, h2 { font-family:'PingFang SC', sans-serif; }

4.3 Attribute Selectors

a[href] { color:blue; }
a[href="https://example.com"] { font-weight:bold; }
a[href*="example"] { color:green; }
a[href^="https"] { /* security icon */ }
a[href$=".pdf"] { /* PDF icon */ }

4.4 Pseudo‑class Selectors

.btn:hover { background:#0052d9; color:#fff; }
input:focus { outline:2px solid #0052d9; border-color:#0052d9; }
.btn:active { transform:scale(0.98); }
li:first-child { border-top:none; }
li:last-child { border-bottom:none; }
tr:nth-child(even) { background:#f5f5f5; }
p:only-child { text-align:center; }
div:empty { display:none; }

4.5 Pseudo‑element Selectors

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

p::first-letter { font-size:3em; float:left; line-height:0.8; }

.icon::before { content:'★'; color:gold; margin-right:4px; }

.required::after { content:' *'; color:red; }

::selection { background:#0052d9; color:white; }

5. Cascade and Specificity

When multiple rules target the same element, CSS uses specificity to decide which rule wins.

Specificity Order (High → Low)

!important > Inline style > ID selector > Class / pseudo‑class / attribute selector > Tag / pseudo‑element selector

Numeric representation (a,b,c,d): !important – highest, use sparingly.

Inline style="" – 1000.

ID #id – 100.

Class, attribute, pseudo‑class – 10.

Tag, pseudo‑element – 1.

Universal * – 0.

/* Specificity: 1 (div) */
div { color:black; }

/* Specificity: 10 (.title) */
.title { color:blue; }

/* Specificity: 11 (div.title) */
div.title { color:green; }

/* Specificity: 100 (#main) */
#main { color:red; }

/* !important overrides everything unless the other rule also has !important */
p { color:pink !important; }

Practical tip: Avoid overusing !important as it harms maintainability; prefer semantic class names to control specificity.

Inheritance

Some properties inherit from parent elements (e.g., font, color, line‑height):

body {
  font-family:'PingFang SC', -apple-system, sans-serif;
  font-size:14px;
  color:#333;
  line-height:1.6;
}

Properties that do not inherit include margin, padding, border, width, background, etc.

6. Box Model – The Foundation of Layout

Every element occupies a rectangular box consisting of margin, border, padding, and content.

┌─────────────────────────────┐
│          margin              │
│  ┌───────────────────────┐ │
│  │        border           │ │
│  │ ┌─────────────────┐   │ │
│  │ │   padding       │   │ │
│  │ │ ┌───────────┐   │   │ │
│  │ │ │ content │   │   │ │
│  │ │ └───────────┘   │   │ │
│  │ └─────────────────┘   │ │
│  └───────────────────────┘ │
└─────────────────────────────┘

box-sizing: Two Box Models

/* Default: content-box */
.box-content {
  box-sizing: content-box;
  width:200px; padding:20px; border:2px solid #ccc; /* actual width = 200+40+4 = 244px */
}

/* Recommended: border-box */
.box-border {
  box-sizing:border-box;
  width:200px; padding:20px; border:2px solid #ccc; /* actual width = 200px */
}

/* Global reset in projects */
*, *::before, *::after { box-sizing:border-box; }

Margin Collapsing (Collapse)

Adjacent vertical margins merge, taking the larger value:

p { margin-bottom:20px; }
p + p { margin-top:10px; } /* actual spacing is 20px, not 30px */

Solution: use padding instead, or layout with flex / grid which prevents collapse.

7. Common Text and Color Properties

Color Representation

.example {
  /* Keywords */
  color:red;
  color:transparent;

  /* Hex (most common) */
  color:#ff0000;
  color:#f00;          /* shorthand */
  color:#ff000080;    /* with alpha */

  /* RGB / RGBA */
  color:rgb(255,0,0);
  color:rgba(255,0,0,0.5);

  /* HSL */
  color:hsl(0,100%,50%);
  color:hsla(0,100%,50%,0.5);

  /* Modern CSS Color Level 4 */
  color:rgb(255 0 0 / 50%);
}

Text Styling

.article {
  font-family:'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size:16px;
  font-weight:400;   /* normal */
  font-weight:700;   /* bold */
  font-weight:300;   /* light */
  line-height:1.8;   /* unitless */
  letter-spacing:0.05em;
  color:#333;
  text-align:left | center | right | justify;
  text-decoration:none | underline | line-through;
  text-transform:uppercase | lowercase | capitalize;
  white-space:nowrap; overflow:hidden; text-overflow:ellipsis; /* single‑line truncation */
}

/* Multi‑line truncation (WebKit) */
.multi-ellipsis {
  display:-webkit-box;
  -webkit-line-clamp:3;
  -webkit-box-orient:vertical;
  overflow:hidden;
}

8. CSS Units in Detail

.units-demo {
  /* Absolute */
  width:200px;               /* pixels */
  font-size:12pt;           /* points, for print */

  /* Relative */
  font-size:1em;            /* relative to parent */
  font-size:1rem;           /* relative to root */
  width:50%;                /* relative to parent width */

  /* Viewport */
  width:100vw;               /* 100% of viewport width */
  height:100vh;             /* 100% of viewport height */
  font-size:2vmin;          /* 2% of the smaller viewport dimension */

  /* Modern viewport units */
  height:100dvh;            /* dynamic viewport height */
  height:100svh;            /* small viewport height */
  height:100lvh;            /* large viewport height */
}

em vs rem Practice

/* Set root font size */
html { font-size:16px; /* 1rem = 16px */ }

/* em – relative to parent */
.parent { font-size:20px; }
.parent .child { font-size:1.5em; /* =30px */ }

/* rem – relative to root */
.title { font-size:1.5rem; /* =24px */ margin-bottom:1rem; /* =16px */ }

Practical advice:

Use px or % for layout dimensions.

Use rem for font sizes (easier global scaling).

Use rem or px for spacing.

9. Background Properties

.hero {
  background-color:#f5f5f5;
  background-image:url('/images/banner.jpg');
  background-repeat:no-repeat;      /* no repeat */
  background-repeat:repeat-x;      /* horizontal repeat */
  background-position:center center;
  background-size:cover;           /* cover */
  background-attachment:fixed;     /* parallax effect */
  /* Shorthand (recommended) */
  background:url('/images/banner.jpg') center/cover no-repeat #f5f5f5;
}

.gradient {
  /* Linear gradient */
  background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);
  /* Radial gradient */
  background:radial-gradient(circle,#667eea,#764ba2);
  /* Multiple layers */
  background:
    url('/icons/logo.png') top left no-repeat,
    linear-gradient(135deg,#667eea,#764ba2);
}

10. Borders and Border‑Radius

.card {
  border:1px solid #e8e8e8;               /* shorthand */
  border-width:1px; border-style:solid; border-color:#e8e8e8;
  border-top:2px solid #0052d9; border-bottom:none;
  border-radius:8px;                     /* all corners */
  border-radius:8px 8px 0 0;             /* TL TR BR BL */
  border-radius:50%;                     /* circle (needs equal width/height) */
  border-radius:100px;                  /* pill button */
}

input:focus { outline:2px solid #0052d9; outline-offset:2px; }

11. The display Property

The display property determines an element’s layout behavior.

/* Block – occupies full line, can set width/height */
.block { display:block; }

/* Inline – does not break line, cannot set width/height */
.inline { display:inline; }

/* Inline‑block – does not break line, can set width/height */
.inline-block { display:inline-block; }

/* Flexbox – for flexible layouts (covered later) */
.flex { display:flex; }

/* Grid – for grid layouts (covered later) */
.grid { display:grid; }

/* Hide element (no space) */
.hidden { display:none; }

/* Table display values */
.table { display:table; }
.table-cell { display:table-cell; }

Comparison:

/* Hide and remove from layout */
.gone { display:none; }

/* Hide but keep space */
.invisible { visibility:hidden; }

/* Transparent but still interactive */
.transparent { opacity:0; }

12. Positioning System

/* Static (default) – does not respond to top/left */
.static { position:static; }

/* Relative – offset from its original place, still occupies original space */
.relative { position:relative; top:10px; left:20px; }

/* Absolute – removed from flow, positioned relative to nearest non‑static ancestor */
.absolute { position:absolute; top:0; right:0; }

/* Fixed – positioned relative to viewport, stays on scroll */
.fixed-header { position:fixed; top:0; left:0; width:100%; z-index:1000; }

/* Sticky – toggles between relative and fixed while scrolling */
.sticky-header { position:sticky; top:0; background:white; z-index:100; }

Classic use case: absolute centering

/* Method 1: absolute + transform */
.centered { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); }

/* Method 2: absolute + margin:auto */
.centered-v2 { position:absolute; inset:0; margin:auto; width:200px; height:100px; }

13. overflow and Scrolling

.container {
  overflow:visible;   /* default */
  overflow:hidden;    /* clip overflow */
  overflow:scroll;    /* always show scrollbar */
  overflow:auto;      /* show when needed (recommended) */
  overflow-x:hidden;
  overflow-y:auto;
}

/* Custom scrollbar (WebKit) */
.custom-scroll::-webkit-scrollbar { width:6px; }
.custom-scroll::-webkit-scrollbar-track { background:#f1f1f1; }
.custom-scroll::-webkit-scrollbar-thumb { background:#ccc; border-radius:3px; }
.custom-scroll::-webkit-scrollbar-thumb:hover { background:#999; }

14. A Complete Card Component Example

Integrating the concepts into a real component:

<div class="article-card">
  <div class="article-card__cover">
    <img src="cover.jpg" alt="Article cover" />
    <span class="article-card__badge">Hot</span>
  </div>
  <div class="article-card__body">
    <h3 class="article-card__title">CSS from Beginner to Mastery</h3>
    <p class="article-card__excerpt">This article gives a comprehensive view of core CSS concepts, from selectors to the box model...</p>
    <div class="article-card__footer">
      <span class="article-card__author">leon.wang</span>
      <a class="article-card__link" href="#">Read full article →</a>
    </div>
  </div>
</div>

*, *::before, *::after { box-sizing:border-box; }

.article-card { width:320px; border-radius:12px; overflow:hidden; background:#fff; box-shadow:0 4px 16px rgba(0,0,0,0.08); transition:box-shadow 0.3s, transform 0.3s; }
.article-card:hover { box-shadow:0 8px 32px rgba(0,0,0,0.16); transform:translateY(-4px); }
.article-card__cover { position:relative; height:180px; overflow:hidden; }
.article-card__cover img { width:100%; height:100%; object-fit:cover; transition:transform 0.3s; }
.article-card__cover img:hover { transform:scale(1.05); }
.article-card__badge { position:absolute; top:12px; right:12px; padding:2px 8px; background:#ff4d4f; color:#fff; font-size:12px; border-radius:100px; }
.article-card__title { margin:0 0 8px; font-size:16px; font-weight:600; color:#1a1a1a; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
.article-card__excerpt { margin:0 0 12px; font-size:13px; color:#999; line-height:1.6; display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; }
.article-card__footer { display:flex; justify-content:space-between; align-items:center; }
.article-card__author { font-size:13px; color:#666; }
.article-card__link { font-size:13px; color:#0052d9; text-decoration:none; font-weight:500; }
.article-card__link:hover { text-decoration:underline; }

Conclusion

Selectors: basic, combinators, attributes, pseudo‑classes, pseudo‑elements.

Cascade & Specificity:

!important > inline > ID > class/attribute/pseudo‑class > tag/pseudo‑element

.

Box Model: use box-sizing:border-box globally.

Units: px for layout, rem for fonts, vw/vh for viewport dimensions.

Positioning: static, relative, absolute, fixed, sticky.

Text Styling: font family, weight, line‑height, truncation techniques.

Series Navigation

Part 1 (current): CSS basics – selectors, box model, positioning.

Part 2: Full CSS layout guide – Flexbox and Grid.

Part 3: CSS animations and responsive design.

Part 4: CSS preprocessors – Less and SCSS in practice.

Part 5: Tailwind CSS – utility‑first framework.

Part 6: Modern CSS features and future trends.

Part 7: Comprehensive CSS solutions in React.

Part 8: CSS engineering and best practices.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

FrontendLayoutcssStylingSelectorsBox Model
CodeNotes
Written by

CodeNotes

Discuss code and AI, and document daily life and personal growth.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.