1. 程式人生 > >html和css實現透明div上的div不透明,也可說父div透明,子div不透明

html和css實現透明div上的div不透明,也可說父div透明,子div不透明

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中顯示的顏色也一樣,但是在瀏覽器中顯示的顏色仔細看卻有差別,不知道是為什麼,如果有人知道原因,麻煩請告知,謝謝啦~~~