Opacity Parent not child content
Cách chỉnh nền trong suốt của thẻ Div lớn mà không ảnh hưởng tới thẻ div con bên trong.
Đây là một thủ thuật CSS khá hay. Giúp tạo Opacity trong suốt đẹp mắt. Trong hướng dẫn này tôi sẽ đưa ra hai cách giúp bạn thực hiện thủ thuật CSS này :
Đầu tiên tôi có có CSS :
body{background:#FFF8DC}
.parent-div { width:1000px; height:600px; padding:10px; color:black; font-size:30px;text-align:center; position:relative}
.child-div {width:500px; height:300px; margin:100px auto; font-size: 30px; line-height:300px; text-align:center; background:#8BC43F;position:relative;}
Và HTML như sau :
<div class="parent-div"> Nội dung cha
<div class="child-div">
Nội dung con
</div>
</div>
Kết quả thu được :
-----------------------------------------------------------------------------------------------------------
Cách 1 :
Thêm CSS cho parent-div như sau :
.parent-div { width:500px; height:400px; padding:10px; color:white; font-size:30px;text-align:center; position:relative}
.parent-div:after{position:absolute; background:rgba(0,0,0,0.5); width:500px; height:400px; top:0; left:0; content:''; color:white}.child-div {color:black; width:400px; height:300px; margin:40px auto; font-size: 30px; line-height:300px; text-align:center; background:#8BC43F;position:relative; z-index:1}
Để ý các thuộc tính màu đỏ mà tôi thêm vào.
Cách 2 :
Thêm CSS cho parent-div như sau. Cách này có vẻ hiệu quả hơn mà không làm ảnh hưởng tới các thuộc tính khác như position hay width...Tôi thường sử dụng cách này :
Bạn chỉ cần bổ sung thuộc tính sau cho class .parent-div :
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF);
/* For IE8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF)";
/* 50% opacity for mozilla */
background: rgba(0, 0, 0, 0.5);
Tức là ta sẽ có :
.parent-div { width:500px; height:400px; padding:10px; color:white; font-size:30px;text-align:center; position:relative; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF);
/* For IE8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF)";
/* 50% opacity for mozilla */
background: rgba(0, 0, 0, 0.5);
}
.child-div {color:black; width:400px; height:300px; margin:40px auto; font-size: 30px; line-height:300px; text-align:center; background:#8BC43F;position:relative; z-index:1}
OK. Chúc bạn thực hiện thành công các thao tác trong hướng dẫn này.
(M.Anh - Erhay. Vui lòng ghi rõ nguồn Erhay khi bạn phát hành thông tin từ trang này)


Bài viết rất bổ ích ,xin cảm ơn
ReplyDeleteYou are welcome.
Deletequá bổ ích, cảm ơn bạn nhiều!
ReplyDeletecách 2 làm sao để đổi màu background thành màu khác dược :(
ReplyDeletenó cứ mặc định là màu đen
Bạn có thể vào đây để xem mã rgba nhé http://www.css3maker.com/css-3-rgba.html
Delete