Cẩm nang nhanh — HTML, CSS, JavaScript

Trang này tóm tắt các thẻ HTML, thuộc tính CSS và API JavaScript hay dùng nhất — dùng như tài liệu tham khảo nhanh khi cần tra cứu.


HTML — Thẻ thiết yếu

Cấu trúc trang

Thẻ Mô tả
<!DOCTYPE html> Khai báo HTML5
<html lang="vi"> Phần tử gốc, khai báo ngôn ngữ
<head> Metadata: title, meta, link CSS, script
<body> Nội dung hiển thị ra màn hình
<header> Tiêu đề trang hoặc section
<nav> Vùng điều hướng (menu)
<main> Nội dung chính (duy nhất trong trang)
<article> Nội dung độc lập (bài viết, bình luận)
<section> Phân đoạn trang theo chủ đề
<aside> Nội dung phụ, sidebar
<footer> Chân trang

Văn bản & nội dung

Thẻ Mô tả
<h1><h6> Tiêu đề cấp 1–6
<p> Đoạn văn
<strong> Nội dung quan trọng (in đậm + ngữ nghĩa)
<em> Nội dung nhấn mạnh (in nghiêng + ngữ nghĩa)
<a href="url"> Liên kết
<img src="url" alt="text"> Hình ảnh
<ul> / <ol> / <li> Danh sách không thứ tự / có thứ tự / mục
<dl> / <dt> / <dd> Danh sách định nghĩa
<table> / <tr> / <th> / <td> Bảng
<blockquote> Trích dẫn dài
<code> Code inline
<pre> Code block (giữ nguyên khoảng trắng)
<br> Ngắt dòng
<hr> Đường kẻ ngang

Form

Thẻ / Thuộc tính Mô tả
<form action method> Container form
<input type="text"> Ô nhập văn bản
<input type="email"> Ô nhập email (tự validate)
<input type="password"> Mật khẩu (ẩn ký tự)
<input type="checkbox"> Hộp chọn nhiều
<input type="radio"> Chọn một trong nhóm
<input type="file"> Chọn tệp
<input type="submit"> Nút gửi
<textarea> Vùng nhập nhiều dòng
<select> / <option> Danh sách thả xuống
<label for="id"> Nhãn cho input
<button type="submit/reset/button"> Nút bấm
required Bắt buộc nhập
placeholder Văn bản gợi ý
disabled / readonly Vô hiệu hoá / chỉ đọc

Meta tags quan trọng

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Mô tả trang web — hiện trong kết quả tìm kiếm">
<meta property="og:title" content="Tiêu đề cho mạng xã hội">
<meta property="og:image" content="url-ảnh-preview">
<title>Tiêu đề trang</title>
<link rel="canonical" href="https://example.com/url-chinh-thuc">
<link rel="stylesheet" href="style.css">

CSS — Thuộc tính hay dùng

Box Model

box-sizing: border-box;            /* padding/border tính trong width */
width: 300px; height: auto;
max-width: 100%;                   /* Không tràn container */
padding: 1rem;                     /* Trong: 1rem tất cả 4 cạnh */
margin: 0 auto;                    /* Ngoài: căn giữa theo chiều ngang */
border: 1px solid #ddd;
border-radius: 8px;

Typography

font-family: 'Roboto', sans-serif;
font-size: 1rem;       /* 16px mặc định */
font-weight: 400;      /* 400=normal, 700=bold */
font-style: italic;
line-height: 1.6;      /* Khoảng cách dòng (nhân với font-size) */
letter-spacing: 0.02em;
text-align: left|center|right|justify;
text-decoration: none|underline;
text-transform: none|uppercase|lowercase|capitalize;
color: #333;

Display & Visibility

display: block|inline|inline-block|flex|grid|none;
visibility: visible|hidden;     /* hidden vẫn giữ chỗ */
opacity: 0;                     /* 0=trong suốt, 1=đục */
overflow: visible|hidden|scroll|auto;

Flexbox

/* Container */
display: flex;
flex-direction: row|column;
justify-content: flex-start|center|flex-end|space-between|space-around;
align-items: stretch|center|flex-start|flex-end|baseline;
flex-wrap: nowrap|wrap;
gap: 1rem;

/* Item */
flex: 1;             /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
flex: 0 0 200px;     /* Cố định 200px */
align-self: auto|center|flex-start|flex-end;
order: 0;

CSS Grid

/* Container */
display: grid;
grid-template-columns: 1fr 2fr 1fr;               /* 3 cột tỉ lệ 1:2:1 */
grid-template-columns: repeat(3, 1fr);            /* 3 cột đều nhau */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* Responsive */
grid-template-rows: auto;
grid-template-areas: "header header" "sidebar main" "footer footer";
gap: 1rem;

/* Item */
grid-column: 1 / 3;          /* Từ cột 1 đến 3 */
grid-row: 1 / 2;
grid-area: header;            /* Dùng với template-areas */

Position

position: static;            /* Mặc định — theo flow */
position: relative;          /* Giữ chỗ, có thể dùng top/left/right/bottom */
position: absolute;          /* Ra khỏi flow, tính từ ancestor positioned gần nhất */
position: fixed;             /* Ra khỏi flow, tính từ viewport */
position: sticky;            /* Như relative, dính lại khi scroll qua */

top: 0; right: 0; bottom: 0; left: 0;
z-index: 10;                 /* Lớp chồng lên (số lớn hơn = trên) */

Background & Color

color: #333;                              /* Màu chữ */
background-color: rgba(0, 0, 0, 0.5);    /* Màu nền */
background-image: url('img.jpg');
background-size: cover|contain|auto;
background-position: center;
background-repeat: no-repeat;
/* Gradient */
background: linear-gradient(135deg, #4472c4, #6fa3ef);
background: radial-gradient(circle, #fff, #eee);

Transition & Animation

/* Transition */
transition: all 0.3s ease;
transition: color 0.2s, background 0.3s ease-in-out;

/* Animation */
@keyframes slideIn {
  from { transform: translateX(-100%); opacity: 0; }
  to   { transform: translateX(0);     opacity: 1; }
}
animation: slideIn 0.5s ease forwards;

/* Transform */
transform: translateX(20px) translateY(-50%) rotate(45deg) scale(1.2);

CSS Custom Properties (Variables)

:root {
  --primary: #4472c4;
  --spacing: 1rem;
}
.btn { background: var(--primary); padding: var(--spacing); }

Media Queries (Responsive)

/* Mobile-first: style mặc định cho mobile, mở rộng cho màn lớn */
@media (min-width: 768px)  { /* tablet+ */ }
@media (min-width: 1024px) { /* desktop+ */ }

/* Breakpoints Bootstrap 5 */
/* sm: 576px | md: 768px | lg: 992px | xl: 1200px | xxl: 1400px */

JavaScript — API trình duyệt hay dùng

DOM Selection

document.getElementById('id')              // Một phần tử theo id
document.querySelector('.class')           // Phần tử đầu tiên theo CSS selector
document.querySelectorAll('div.card')      // Tất cả phần tử theo CSS selector
document.createElement('div')             // Tạo phần tử mới
element.closest('.parent')                // Tìm ancestor gần nhất khớp selector

DOM Manipulation

el.textContent = 'text'                   // Nội dung text (an toàn, không render HTML)
el.innerHTML   = '<b>html</b>'            // Nội dung HTML (cẩn thận XSS)
el.classList.add('active')               // Thêm class
el.classList.remove('active')            // Xoá class
el.classList.toggle('dark')              // Thêm/xoá class
el.classList.contains('btn')            // Kiểm tra có class không
el.setAttribute('href', '/url')         // Set thuộc tính
el.getAttribute('href')                  // Lấy thuộc tính
el.style.color = 'red'                   // Style inline
parent.appendChild(child)               // Thêm phần tử con cuối
parent.removeChild(child)               // Xoá phần tử con
el.remove()                             // Xoá phần tử khỏi DOM

Events

el.addEventListener('click', function(event) {
  event.preventDefault()                 // Ngăn hành vi mặc định (a, form)
  event.stopPropagation()               // Ngăn bubble lên parent
  console.log(event.target)             // Phần tử được click
  console.log(event.currentTarget)      // Phần tử gắn listener
})
el.removeEventListener('click', handler)

// Các sự kiện phổ biến:
// click, dblclick, mouseenter, mouseleave, mouseover
// keydown, keyup, keypress
// input, change, submit, focus, blur
// scroll, resize (window)
// DOMContentLoaded, load (window)

Fetch API

// GET
fetch('/api/data')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err))

// POST (async/await)
async function postData(url, payload) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

Storage

localStorage.setItem('key', JSON.stringify(value))    // Lưu vĩnh viễn
localStorage.getItem('key')                            // Lấy (string)
JSON.parse(localStorage.getItem('key'))               // Lấy object
localStorage.removeItem('key')                        // Xoá
localStorage.clear()                                   // Xoá tất cả

// sessionStorage: tương tự nhưng chỉ tồn tại trong phiên trình duyệt

ES6+ Shorthand

// Destructuring
const { name, age = 0 } = person
const [first, ...rest]   = array

// Spread
const merged = { ...obj1, ...obj2 }
const copy   = [...arr1, ...arr2]

// Template literal
const msg = `Xin chào ${name}, bạn ${age} tuổi`

// Arrow function
const double = x => x * 2
const add    = (a, b) => a + b

// Optional chaining
const city = user?.address?.city     // undefined nếu thiếu

// Nullish coalescing
const name = user.name ?? 'Ẩn danh' // 'Ẩn danh' nếu null/undefined

// Array methods
arr.map(x => x * 2)                  // Biến đổi từng phần tử → mảng mới
arr.filter(x => x > 0)               // Lọc → mảng mới
arr.reduce((sum, x) => sum + x, 0)  // Gộp thành một giá trị
arr.find(x => x.id === 1)            // Phần tử đầu tiên khớp
arr.findIndex(x => x.id === 1)       // Index phần tử đầu tiên khớp
arr.some(x => x > 0)                 // true nếu có ít nhất 1 khớp
arr.every(x => x > 0)                // true nếu tất cả khớp
arr.includes(value)                  // true nếu có chứa value
arr.flat()                           // Làm phẳng 1 cấp
arr.flatMap(fn)                      // map() + flat(1)

Playground thử nhanh

Kết quả
<div class="demo">
  <h2>Playground thử nhanh</h2>
  <p>Chỉnh sửa HTML, CSS và JS rồi xem kết quả ngay bên phải.</p>

  <div class="card-row">
    <div class="card">🎨 HTML</div>
    <div class="card">💅 CSS</div>
    <div class="card">⚡ JS</div>
  </div>

  <button id="btn">Click me (0)</button>
</div>
* { box-sizing: border-box; font-family: sans-serif; }
body { padding: 1.5rem; background: #f0f4f8; }
h2   { color: #4472c4; margin-bottom: .5rem; }
p    { color: #666; margin-bottom: 1rem; }

.card-row { display: flex; gap: .75rem; margin-bottom: 1rem; }
.card {
  flex: 1; padding: .75rem;
  background: white; border-radius: 8px;
  text-align: center; font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,.1);
  transition: transform .2s;
  cursor: default;
}
.card:hover { transform: translateY(-3px); }

button {
  padding: .5rem 1.25rem;
  background: #4472c4; color: white;
  border: none; border-radius: 6px;
  font-size: 1rem; cursor: pointer;
}
button:hover { background: #3260ad; }
button.clicked { background: #2ecc71; }
const btn = document.getElementById('btn');
let count = 0;
btn.addEventListener('click', () => {
  count++;
  btn.textContent = `Click me (${count})`;
  btn.classList.toggle('clicked', count % 2 === 0);
});

Bình luận