CSS 怎样让 div 重叠? 下面本篇文章给大家介绍一下使用 CSS 让 DIV 重叠并按想要顺序重叠的方法. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
在 CSS 中, 想让 DIV 重叠, 甚至按想要顺序重叠, 主要使用 position 属性和 z-index 属性, 通过绝对定位来实现.
重叠样式需要主要 CSS 样式解释
1,z-index 重叠顺序属性
2,position:relative 和 position:absolute 设置对象属性为可定位 (可重叠)
3,left,right,top,bottom 绝对定位具体位置设置
配合的样式
- ,CSS width
- ,CSS height
3,background 为了观察效果, 我们对不同 DIV 设置不同背景颜色进行区别
示例 1: 未排层叠顺序
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8" />
- <style>
- .div-relative{ position:relative; color:#000; border:1px solid #000; width:500px;
- height:400px; } .div-a{ position:absolute; left:30px; top:30px; background:#F00;
- width:200px; height:100px; } /* CSS 注释说明: 背景为红色 */ .div-b{ position:absolute;
- left:50px; top:60px; background:#FF0; width:400px; height:200px; } /* 背景为黄色
- */ .div-c{ position:absolute; left:80px; top:80px; background:#00F; width:300px;
- height:300px; } /* DIV 背景颜色为蓝色 */
- </style>
- </head>
- <body>
- <div class="div-relative">
- <div class="div-a">
- 我背景为红色
- </div>
- <div class="div-b">
- 我背景为黄色
- </div>
- <div class="div-c">
- 我背景为蓝色
- </div>
- </div>
- </body>
- </HTML>
效果图:
说明:
我们使用 position 实现绝对定位, 对父级设置 position:relative 属性, 对其子级设置 position:absolute 加上 left 或 right 和 top 或 bottom 实现子级在父级内任意定位. 在原始情况下重叠是按 DIV 代码本身顺序排列, 越后输入的 DIV 盒子其越靠前 (浮在上面). 除了改变源代码本身 div 代码在 HTML 顺序, 我们还可以使用 CSS z-index 实现 DIV 层排列顺序.
示例 2: 控制 DIV 重叠顺序
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="utf-8" />
- <style>
- .div-relative{ position:relative; color:#000; border:1px solid #000; width:500px;
- height:400px; } .div-a{ position:absolute; left:30px; top:30px; z-index:100;
- background:#F00; width:200px; height:100px; } /* div 背景色为红色 */ .div-b{
- position:absolute; left:50px; top:60px; z-index:80; background:#FF0; width:400px;
- height:200px; } /* 背景为黄色 */ .div-c{ position:absolute; left:80px; top:80px;
- z-index:70; background:#00F; width:300px; height:300px; } /* 背景为蓝色 */
- </style>
- </head>
- <body>
- <div class="div-relative">
- <div class="div-a">
- 我背景为红色
- </div>
- <div class="div-b">
- 我背景为黄色
- </div>
- <div class="div-c">
- 我背景为蓝色
- </div>
- </div>
- </body>
- </HTML>
效果图:
z-index 的值为正整数值, 数字越大对应对象层越浮上层 (越靠前).
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/css3/17003.html