使用 CSS 可以轻松地为两个 <div> 元素创建叠加效果。
这可以通过结合 CSS position 和 z-index 属性来完成。
元素的 z-index 定义了它在堆叠上下文中的顺序。
在我们的示例中,我们将使用 position 属性的“absolute”和“relative”值,并添加 z-index 属性来指定定位元素的堆叠顺序。
那么,让我们开始吧!
创建 HTML
- 使用名为“container”的类的 <div> 元素。
- 在第一个元素中添加另外两个 <div> 元素。也为它们添加类。
<div class="container"> <div class="box"></div> <div class="box overlay"></div> </div>
添加 CSS
- 指定“容器”类的宽度和高度。
将位置设置为“相对”并添加边距属性。
- 将“box”类的宽度和高度都设置为“100%”。用“绝对”值指定位置。添加 top 和 left 属性。
另外,指定“box”类的背景和不透明度。
- 使用 z-index、margin 和 background 属性设置“overlay”类的样式。
.container { width: 150px; height: 150px; position: relative; margin: 30px; } .box { width: 100%; height: 100%; position: absolute; top: 0; left: 0; opacity: 0.7; background: #0057e3; } .overlay { z-index: 9; margin: 30px; background: #009938; }
现在,我们可以将代码的各个部分组合在一起。
将一个 <div> 覆盖在另一个上的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .container { width: 150px; height: 150px; position: relative; margin: 30px; } .box { width: 100%; height: 100%; position: absolute; top: 0; left: 0; opacity: 0.7; background: #0057e3; } .overlay { z-index: 9; margin: 30px; background: #009938; } </style> </head> <body> <div class="container"> <div class="box"></div> <div class="box overlay"></div> </div> </body> </html>
让我们看另一个例子,我们使用更多的 CSS。
其中我们使用 CSS :hover 伪类添加了一些悬停效果。
将一个 <div> 覆盖在另一个具有悬停效果的示例上:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .container { position: absolute; height: 250px; width: 400px; background-color: #7d807e; } .box1 { color: #fff; padding-top: 60px; padding-left: 50px; font-size: 50px; font-weight: bold; } .box2 { padding-left: 50px; } .box1:hover { z-index: -1; opacity: 0.5; font-size: 30px; text-align: center; transform-style: all; transition-duration: 2s; } .box2:hover { z-index: -1; opacity: 0.3; font-size: 40px; text-align: center; transform-style: all; transition-duration: 2s; } </style> </head> <body> <div class="container"> <div class="box1">onitroad</div> <div class="box2">Learn programming</div> </div> </body> </html>
日期:2020-06-02 22:15:10 来源:oir作者:oir