• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

css实现背景图片透明内容不透明

武飞扬头像
Deca~
帮助5

实现背景图片透明而内容不透明有很多种方法,但是我最常用的是用before伪元素。

大家肯定都知道透明是使用opacity,但opacity会让背景及其子元素的所有内容都透明,比如:

  1.  
    <style>
  2.  
    * {
  3.  
    margin: 0;
  4.  
    padding: 0;
  5.  
    }
  6.  
     
  7.  
    .box1 {
  8.  
    width: 500px;
  9.  
    height: 340px;
  10.  
    position: absolute;
  11.  
    top: 50%;
  12.  
    left: 50%;
  13.  
    margin-left: -250px;
  14.  
    margin-top: -170px;
  15.  
    opacity: 0.5;
  16.  
    background-image: url("./StudyCode/HTML5 CSS3/图片/哈利波特7.png");
  17.  
    }
  18.  
    .box2{
  19.  
    width: 200px;
  20.  
    height: 150px;
  21.  
    font-size: 40px;
  22.  
    font-weight: 500;
  23.  
    position: absolute;
  24.  
    top: 50%;
  25.  
    left: 50%;
  26.  
    margin-left: -100px;
  27.  
    margin-top: -75px;
  28.  
    text-align: center;
  29.  
    line-height: 150px;
  30.  
    letter-spacing: 10px;
  31.  
    }
  32.  
    </style>
  33.  
    </head>
  34.  
     
  35.  
    <body>
  36.  
    <div class="box1">
  37.  
    <div class="box2">哈利波特</div>
  38.  
    </div>
  39.  
    </body>
  40.  
     
  41.  
    </html>
学新通

得到的结果如下:可以看见其中的字体也被透明了

学新通

在上面的css中加上如下代码即可解决:记得把上面的.box1的最后两行代码删掉,不然会覆盖before的内容。

  1.  
    .box1::before{
  2.  
    width: 500px;
  3.  
    height: 340px;
  4.  
    content: "";
  5.  
    /* 一定要加定位,这样z-index才起作用 */
  6.  
    position: absolute;
  7.  
    top: 50%;
  8.  
    left: 50%;
  9.  
    margin-left: -250px;
  10.  
    margin-top: -170px;
  11.  
    z-index: -1;
  12.  
    opacity: 0.5;
  13.  
    background-image: url("./StudyCode/HTML5 CSS3/图片/哈利波特7.png");
  14.  
    }

得到结果:

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhffhjgc
系列文章
更多 icon
同类精品
更多 icon
继续加载