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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aSuncat/article/details/51878812

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

...
    <style>
        div.background
        {
            width:500px;
            height:250px;
            margin:100px;
            border:2px solid black;
            position:relative;
            z-index:100;
        }
        div.transbox
        {
            width:400px;
            height:180px;
            margin:30px 50px;
            border:1px solid #f00;
            opacity:0.3;
            filter:alpha(opacity=60); /* For IE8 and earlier */
            background-color:#f00;
            z-index:101;
        }
        .div1{
            width:200px;
            height:100px;
            position:absolute;
            left:50px;
            top:40px;
            border:1px solid #0f0;
            overflow:hidden;
            z-index:102;
        }
    </style>
</head>
<body>
    <div class="background">
        <div class="transbox"></div>
        <div class="div1">
            This is some text that is placed in the transparent box.
                This is some text that is placed in the transparent box.
                This is some text that is placed in the transparent box.
                This is some text that is placed in the transparent box.
                This is some text that is placed in the transparent box.
        </div>
    </div>
</body>
...

(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;
二、方法二
(代码片段)

    <style>
        div.background
        {
            width:500px;
            height:250px;
            margin:100px;
            border:2px solid black;
            position:relative;
            z-index:100;
        }
        div.transbox
        {
            width:400px;
            height:180px;
            margin:30px 50px;
            border:1px solid rgba(255,0,0,0.3);
            background:rgba(255,0,0,0.3);/*关键代码*/
            z-index:101;
        }
    </style>
</head>
<body>
<div class="background">
    <div class="transbox">
        This is some text that is placed in the transparent box.
            This is some text that is placed in the transparent box.
            This is some text that is placed in the transparent box.
            This is some text that is placed in the transparent box.
            This is some text that is placed in the transparent box.
    </div>
</div>

(2)呈现效果
opacity2
(3)备注:
①这个方法比方法一简单,推荐使用此方法。
②对border和background设置一样的值和透明度,在webstorm中显示的颜色也一样,但是在浏览器中显示的颜色仔细看却有差别,不知道是为什么,如果有人知道原因,麻烦请告知,谢谢啦~~~

展开阅读全文

没有更多推荐了,返回首页