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

วิธีสร้าง Blurry Background Image (พื้นหลังเบลอ) ด้วย CSS

สร้างพื้นหลังรูปภาพเบลอ (Blur) พร้อมข้อความทับบนหน้า ใช้ filter: blur(10px) บน Background Element

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body, html {    height: 100vh;    margin: 0;    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } * {    box-sizing: border-box; } .backgroundImage {    background-image: url("https://images.pexels.com/photos/1172207/pexels-photo-1172207.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500");    filter: blur(10px);    height: 100%;    background-position: center;    background-repeat: no-repeat;    background-size: cover; } .transparentText {    background-color: rgba(0, 0, 0, 0.4);    color: white;    border: 3px solid #f1f1f1;    position: absolute;    top: 40%;    left: 30%;    width: 50%;    padding: 20px;    text-align: center; } </style> </head> <body> <div class="backgroundImage"></div> <div class="transparentText"> <h1>I am Shawn</h1> <h1>I am a web developer</h1> </div> </body> </html>

เทคนิคสำคัญ

  • .backgroundImage { filter: blur(10px); } - เบลอพื้นหลัง 10px
  • แยก Element - Background และ Text แยก Element กัน ไม่ให้ Text โดน Blur ตาม
  • .transparentText { position: absolute; } - วางทับบน Background
  • rgba(0,0,0,0.4) - พื้นหลังข้อความดำโปร่งใส อ่านง่าย

วิธีอื่น: Backdrop-filter (ทันสมัยกว่า)

.overlay {
  backdrop-filter: blur(10px); /* เบลอเฉพาะสิ่งด้านหลัง */
  background: rgba(255,255,255,0.3);
}

backdrop-filter เบลอเฉพาะเนื้อหาด้านหลัง Element นั้น ไม่ต้องแยก Element

Browser Support

  • filter: blur() - รองรับทุก Browser สมัยใหม่
  • backdrop-filter - ต้องใช้ Prefix -webkit-backdrop-filter บน Safari/iOS

ผลลัพธ์

พื้นหลังรูปทิวทัศน์เบลอ 10px ทับกล่องสีดำโปร่งใสตรงกลาง เขียน "I am Shawn / I am a web developer"