css實現背景圖片半透明內容不透明代碼分享

來源:互聯網
上載者:User
本文主要和大家介紹了純css實現背景圖片半透明內容不透明的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考,希望能協助到大家。

最近做一個登陸介面的,突然想使用這種背景圖片透明,而內容不透明的效果,這裡我就說一說我的兩個思路吧。

效果展示

半透明

不透明

常見的失敗做法

最常見的做法事設定元素的opacity,這種設定出來的效果就是內容與背景都事半透明的,嚴重影響視覺效果。

還有就是設定background-color:rgba(),這種方式只能設定背景顏色的透明度。

正確姿勢

我想到兩個方法,第一個就是利用虛擬元素::before,我們通過給虛擬元素添加背景並且將虛擬元素的設定虛擬元素的背景透明度來實現


<!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <title>登陸</title>    <style type="text/css">        body{            background-image:url(images/bird.jpg);            background-repeat: no-repeat;            background-size:100%;        }        .login_box::before{            content:"";            /*-webkit-filter: opacity(50%);              filter: opacity(50%); */            background-image:url(images/love.jpg);            opacity:0.5;//透明度設定            z-index:-1;            background-size:500px 300px;            width:500px;             height:300px;            position:absolute;            //一定要設定position:absolute,這樣才能設定z-index,讓背景處於內容的下一層            top:0px;            left:0px;            border-radius:40px;        }        .login_box{            position:fixed;            left:50%;            top:200px;            width:500px;            height:300px;            margin-left:-250px;            border-radius:40px;            box-shadow: 10px 10px 5px #888;            border:1px solid #666;            text-align:center;        }        form{            display:inline-block;            margin-top:100px;        }        input{            display:block;            width:250px;            height:30px;            background-color: #888;            border:1px solid #fee;            outline:none;            border-radius:10px;        }        input[type="submit"]{            width:100px;            height:30x;            margin-left: 70px;            background-color: #ccc;        }        span{            color:red;            font-size:15px;        }    </style> </head> <body>    <p class="login_box">        <form action=<?php echo $_SERVER['PHP_SELF'] ?> method="post">            <input type="text" name="nickname">            <span><?php echo $nameERR; ?></span>            <br>            <input type="password" name="password">            <span><?php echo $passwordERR; ?></span>            <br>            <input type="submit" value="登陸">        </form>     </p> </body> </html>

還有一種方法與虛擬元素異曲同工,我們可以通過設定不通的p,裡面的p放置內容,父級p設定背景,然後給它設定透明度,大概布局如下:


<p class="bg">    <p class="content">    一些內容    </p></p>

這樣也可以達到同樣的效果。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.