html和css实现透明div上的div不透明,也可说父div透明,子div不透明

短命女 2022-07-21 00:22 312阅读 0赞

css:实现透明div上的div不透明,也可说父div透明,子div不透明,但这里并不是严格的父子关系,只是看起来像是父子关系。
一、方法一:
(1)代码片段:

  1. ...
  2. <style>
  3. div.background
  4. {
  5. width:500px;
  6. height:250px;
  7. margin:100px;
  8. border:2px solid black;
  9. position:relative;
  10. z-index:100;
  11. }
  12. div.transbox
  13. {
  14. width:400px;
  15. height:180px;
  16. margin:30px 50px;
  17. border:1px solid #f00;
  18. opacity:0.3;
  19. filter:alpha(opacity=60); /* For IE8 and earlier */
  20. background-color:#f00;
  21. z-index:101;
  22. }
  23. .div1{
  24. width:200px;
  25. height:100px;
  26. position:absolute;
  27. left:50px;
  28. top:40px;
  29. border:1px solid #0f0;
  30. overflow:hidden;
  31. z-index:102;
  32. }
  33. </style>
  34. </head>
  35. <body>
  36. <div class="background">
  37. <div class="transbox"></div>
  38. <div class="div1">
  39. This is some text that is placed in the transparent box.
  40. This is some text that is placed in the transparent box.
  41. This is some text that is placed in the transparent box.
  42. This is some text that is placed in the transparent box.
  43. This is some text that is placed in the transparent box.
  44. </div>
  45. </div>
  46. </body>
  47. ...

(2)呈现效果:
opacity
(3)备注:
①对3个div设置宽度,高度,避免div因为没有内容而使高度为0。
②对父div设置position:relative;子div中.transbox可设置position:absolute;不过在这里不设置也不影响效果。子div中.div1一定要设置position:absolute;这样才能使.div1看起来是在transbox上面的div。
③对子div中.transbox设置透明度,会使背景有一定的透明度,但是不会影响到子div中.div1的透明度,从而实现透明div上的div不透明。
④对三个div是否设置z-index,对这里的效果没有影响,如果每个div都写字,并且涉及到覆盖的话,就会用到z-index;
二、方法二
(代码片段)

  1. <style>
  2. div.background
  3. {
  4. width:500px;
  5. height:250px;
  6. margin:100px;
  7. border:2px solid black;
  8. position:relative;
  9. z-index:100;
  10. }
  11. div.transbox
  12. {
  13. width:400px;
  14. height:180px;
  15. margin:30px 50px;
  16. border:1px solid rgba(255,0,0,0.3);
  17. background:rgba(255,0,0,0.3);/*关键代码*/
  18. z-index:101;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <div class="background">
  24. <div class="transbox">
  25. This is some text that is placed in the transparent box.
  26. This is some text that is placed in the transparent box.
  27. This is some text that is placed in the transparent box.
  28. This is some text that is placed in the transparent box.
  29. This is some text that is placed in the transparent box.
  30. </div>
  31. </div>

(2)呈现效果
opacity2
(3)备注:
①这个方法比方法一简单,推荐使用此方法。
(aSuncat:20160711)②对border和background设置一样的值和透明度,在webstorm中显示的颜色也一样,但是在浏览器中显示的颜色仔细看却有差别,不知道是为什么,如果有人知道原因,麻烦请告知,谢谢啦~~~
(aSuncat:20190813)border和background上下重叠后,带有透明度的颜色叠加,相当于border是rgba(255,0,0,0.6),所以颜色会深一点.border应该为rgba(255,0,0,0),两处的颜色就会一样。

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读