1、定位的叠放次序(只有定位的盒子才拥有这个属性)
(1)在使用定位布局的时候,可能会出现盒子重叠的情况,此时,可以使用z-index来控制盒子的前后次序。该属性的值可以是正整数、负整数或0,默认是auto,数值越大,盒子越靠上
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; 200px; height: 200px; background-color: yellow; z-index: 5; } .test2 { position: absolute; 200px; height: 200px; background-color: red; z-index: 3; } .test3 { position: absolute; 200px; height: 200px; background-color: black; z-index: -1; } </style> </head> <body> <div class="test1"></div> <div class="test2"></div> <div class="test3"></div> </body> </html>
(2)如果盒子的z-index属性的值相等,那么后来者居上
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; 200px; height: 200px; background-color: yellow; } .test2 { position: absolute; 200px; height: 200px; background-color: red; } .test3 { position: absolute; 200px; height: 200px; background-color: black; } </style> </head> <body> <div class="test1"></div> <div class="test2"></div> <div class="test3"></div> </body> </html>
2、绝对定位的盒子水平居中
加了绝对定位的盒子不能通过margin :0 auto水平居中
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; left: 50%; margin-left: -100px; 200px; height: 200px; background-color: yellow; } </style> </head> <body> <div class="test1"></div> </body> </html>
先将盒子的左侧调整到浏览器的中间位置,然后再向左侧移动盒子宽度的一半
3、定位的特性
(1)绝对定位和浮动类似,行内元素添加绝对定位或固定定位后就可以直接设置高度或宽度
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; 200px; height: 200px; background-color: yellow; } </style> </head> <body> <div class="test1"></div> </body> </html>
(2)块级元素添加绝对定位或固定定位,如果不设置高度或宽度,默认大小是内容的大小
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; background-color: yellow; } </style> </head> <body> <div class="test1">你好</div> </body> </html>
(3)浮动的元素只会压住标准流的盒子,但是不会压住标准流里盒子的文字或图片,但是绝对定位或固定定位会压住标准流的所有内容
浮动:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { float: left; background-color: yellow; 200px; height: 200px; } </style> </head> <body> <div class="test1"></div> <p>早上好,今天是星期一</p> </body> </html>
定位:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test1 { position: absolute; background-color: yellow; 200px; height: 200px; } </style> </head> <body> <div class="test1"></div> <p>早上好,今天是星期一..................</p> </body> </html>