Trong bài viết này mình sẽ hướng dẫn các bạn tạo một khung trong suốt và làm mờ nó chỉ bằng HTML và CSS. Cách tạo cũng khá đơn giản.
Cách tạo
Phần bên ngoài khung chúng ta dùng một hình ảnh làm background (tức là layer bên dưới): background: url(bg.jpg);
. Phần bên trong chúng ta sẽ dùng lại hình đó làm background. Từ đó chúng ta sẽ tạo được hiệu ứng trong suốt. Tuy nhiên cần phải đặt thuộc tính background-attachment: fixed;
để background không bị lệch giữa phần ngoài và phần bên trong khung.
Đồng thời phần khung chúng ta sẽ làm mờ nó bằng thuộc tính: filter: blur(4px);
áp dụng cho phần khung muốn làm mờ.
Phần khung + tất cả nội dung bên trong khung được đặt thuộc tính z-index
với mục đích để phần khung này hiển thị như là một layer phía trên.
Chi tiết
Các bạn có thể xem source ở đây:
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>CSS Blurred Transparent Background</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> </head> <body> <section> <div class="box"> <h2>CSS Blurred Glass / Transparent Div</h2> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Veritatis soluta architecto ad corporis molestiae maiores cumque id eligendi quos quo! Magnam consectetur expedita sint necessitatibus veniam maxime suscipit sit quidem?<br><br> Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam consectetur reiciendis ut totam commodi nostrum odit ex similique veritatis beatae quibusdam vero earum mollitia blanditiis, sapiente magni nisi cum! Nihil!</p> </div> </section> </body> </html>
main.css
body{ margin: 0; padding: 0; font-family: sans-serif; } section{ position: relative; display: flex; justify-content: center; align-items: center; background: url(bg.jpg); background-attachment: fixed; height: 100vh; } section .box{ position: relative; max-width: 600px; padding: 50px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5); overflow: hidden; color: #000; /* sửa color để đổi màu chữ bên trong box trong suốt */ } section .box:before{ content: ''; position: absolute; top: -20px; left: -20px; right: -20px; bottom: -20px; background: url(bg.jpg); background-attachment: fixed; filter: blur(4px); } section .box h2{ position: relative; margin: 0 0 20px; padding: 0; font-size: 48px; text-transform: uppercase; z-index: 2; } section .box p{ position: relative; margin: 0; padding: 0; font-size: 18px; z-index: 2; }
Còn đây là video hướng dẫn chi tiết
Demo và download
Các bạn có thể xem demo và download source code tại đây.