Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo hình học (CSS Shapes): Vuông, Tròn, Tam giác, Tim, Chữ...

Tạo hình học thuần CSS không cần hình ảnh. Tất cả bọc trong <div>.

1. Vuông & Chữ nhật

Mặc định div là hình chữ nhật. Vuông: width = height.

.square { width: 5rem; height: 5rem; background: lime; }
.rectangle { width: 2rem; height: 4rem; background: violet; }

Dùng rem (dựa trên root font-size) để scale dễ dàng.

2. Tròn & Oval (Circle)

.profile-image {
  width: 100px; height: 100px;
  border-radius: 50%;           /* Vuông + 50% = tròn */
  background-image: url(...);
  background-position: center;
  background-size: cover;
}
.oval { width: 150px; height: 80px; border-radius: 50%; }

3. Hình bình hành (Parallelogram)

.parallelogram {
  width: 6rem; height: 1.5rem;
  background: indianred; color: ivory;
  transform: skew(-20deg);     /* Nghiêng -20 độ */
}

Dùng transform: skew(). Nội dung bên trong cũng bị nghiêng theo.

4. Tam giác (Triangle)

Kỹ thuật bordertransparent:

.triangle {
  width: 0; height: 0;
  border-left: 2rem solid transparent;
  border-right: 2rem solid transparent;
  border-bottom: 5rem solid hotpink;
}

Điều chỉnh border-width tạo tam giác các hướng.

5. Trái tim (Heart)

Dùng radial-gradient + linear-gradient trên background, kết hợp ::before cho tỷ lệ:

.heart {
  width: 10rem;
  background: 
    radial-gradient(circle at 60% 65%, goldenrod 64%, transparent 65%) top left,
    radial-gradient(circle at 40% 65%, goldenrod 64%, transparent 65%) top right,
    linear-gradient(to bottom left, goldenrod 43%, transparent 43%) bottom left,
    linear-gradient(to bottom right, goldenrod 43%, transparent 43%) bottom right;
  background-size: 50% 50%; background-repeat: no-repeat;
}
.heart::before { content: ""; display: block; padding-top: 100%; }

Thử đổi % và màu để hiểu cơ chế.

6. Hình đa giác tùy ý: clip-path & polygon()

.letter-t {
  width: 5rem; height: 5rem; background: navajowhite;
  shape-outside: polygon(0 0, 100% 0, 100% 20%, 60% 20%, 60% 100%, 40% 100%, 40% 20%, 0 20%);
  clip-path: polygon(0 0, 100% 0, 100% 20%, 60% 20%, 60% 100%, 40% 80%, 40% 20%, 10% 20%);
}

clip-path: polygon() cắt hình theo tọa độ %. Công cụ hỗ trợ: Clippy (CSS clip-path maker) — vẽ hình trực quan, tự sinh code.

Kết luận

CSS Shapes: border-radius (tròn/oval), transform:skew (bình hành), border (tam giác), gradient + pseudo (tim), clip-path:polygon() (hình tùy ý). Kết hợp tạo UI độc đáo không cần file ảnh.