Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีสร้าง Hero Image (ฮีโร่ อิมเมจ) ด้วย CSS

สร้าง Hero Section (ส่วนบนสุดของเว็บ) พร้อมรูปพื้นหลัง Gradient Overlay, ข้อความตรงกลาง และ CTA Button

ตัวอย่างโค้ด

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body, html {    height: 100%;    margin: 0;    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } *, *::before, *::after {    box-sizing: border-box; } h1 {    font-size: 60px;    font-weight: bolder; } .heroContainer {    background-image: linear-gradient( rgba(185, 255, 243, 0.5), rgba(31, 12, 117, 0.5) ),    url("https://images.pexels.com/photos/670720/pexels-photo-670720.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");    height: 50%;    background-position: center;    background-repeat: no-repeat;    background-size: cover;    position: relative; } .heroCaption {    text-align: center;    position: absolute;    top: 20%;    left: 45%;    color: white; } .heroCaption button {    border: none;    outline: none;    display: inline-block;    padding: 20px;    color: rgb(255, 255, 255);    opacity: 0.8;    font-size: 20px;    background-color: rgb(47, 151, 21);    text-align: center;    cursor: pointer; } .heroCaption button:hover {    opacity: 1; } </style> </head> <body> <div class="heroContainer"> <div class="heroCaption"> <h1>I am Shawn</h1> <h2>And I'm a Web Developer</h2> <button>Contact Me</button> </div> </div> </body> </html>

องค์ประกอบ Hero Section

  1. Background Image - รูปภาพคุณภาพสูง ครอบเต็มพื้นที่
  2. Gradient Overlay - linear-gradient(rgba(...), rgba(...)) ทับบนรูป เพื่อความคอนทราสต์ข้อความ
  3. Height: 50% (หรือ 100vh) - ความสูง Hero
  4. Caption (Content) - ข้อความ + CTA Button จัดกึ่งกลาง
  5. CTA Button - Call to Action สีสว่าง Hover Opacity 1

Gradient Overlay Technique

background-image: 
  linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), /* Dark Overlay */
  url('image.jpg');

Gradient วางก่อน URL -> ทับบนรูป ใช้ RGBA ควบคุมความโปร่งใส

Responsive Hero

@media (max-width: 768px) {
  .heroContainer { height: 60vh; }
  h1 { font-size: 40px; }
  .heroCaption { left: 50%; transform: translateX(-50%); }
}

ผลลัพธ์

Hero สูง 50% VH รูปพื้นหลังทับ Gradient ม่วง-ฟ้า ข้อความ "I am Shawn / Web Developer" ปุ่ม Contact Me สีเขียว