定位
浮动更多的用于对模块化(无具体像素值要求)区域进行整体排版,对于精确到像素值的页面调整需要使用定位,例如:购物车上的数量、消息通知等
属性名 | 描述 |
position:relative; | 相对定位(相对默认位置进行定位,不脱离文档流,仍占据页面位置) |
position:absolute; | 绝对定位(相对第一个带有定位属性的父元素进行定位,默认是浏览器) |
position:fixed; | 相对浏览器进行固定定位 |
相对,绝对定位
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0px;
padding: 0px;
}
.box1{
width: 100px;
height: 100px;
background-color: black;
opacity: 0.5; /*透明度*/
/*绝对定位 不会保留原来的位*/
position: absolute;
left: 150px;
top: 150px;
/*定位:会脱离原来的层,box1这一层被腾空了,别的层就可以上去了,只是不同的层而已,每个都是一层,可以自由动*/
/*相对定位 会保留原来的位置*/
/*position: relative;
left: 150px;
top: 150px;*/
}
.box2{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
固定定位
<head>
<meta charset="UTF-8">
<title></title>
<style>
.divid{
width: 150px;
height: 30px;
background-color: #ff4200;
border-radius:32px ;
text-align: center;
line-height: 31px;
color: white;
position: fixed;/* fixed: [fɪkst] 固定定位*/
top: 220px;
right: 10px;
}
</style>
</head>
<body>
<p>我是天空里的一片云,</p>
<p>偶尔投影在你的波心──</p>
<p>你不必讶异,</p>
<p>更无须欢喜──</p>
<p>在转瞬间消灭了踪影。</p>
<div class="divid">TEL:13140008888</div>
<p>你我相逢在黑夜的海上,</p>
<p>你有你的,我有我的,方向;</p>
<p>你记得也好,</p>
<p>最好你忘掉</p>
<p>在这交会时互放的光亮!</p>
<p>我是天空里的一片云,</p>
<p>偶尔投影在你的波心──</p>
<p>你不必讶异,</p>
<p>更无须欢喜──</p>
<p>在转瞬间消灭了踪影。</p>
堆叠顺序
元素在进行定位时,会出现位置相同的情况,可以通过设置其堆叠顺序决定显示的优先级
语法:z-index 数值越大越靠前
案例一
<style>
img{
position: absolute;
left: 0px;
top: 0px;
z-index: -1; /* 图片就在文字下方*/
}
p{
color: #E91917;
}
</style>
</head>
<body>
<img src="img/江一燕.jpg" width="200px" />
<P>This is some text. This is some text. This is some text.</P>
<P>This is some text. This is some text. This is some text.</P>
<P>This is some text. This is some text. This is some text.</P>
<P>This is some text. This is some text. This is some text.</P>
</body>
案例二
<div></div>
<div></div>
<div></div>
div{
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 300px;
}
div:nth-of-type(1){
z-index: 1;
background-color: #008B8B;
}
div:nth-of-type(2){
z-index: 2;
background-color: #483D8B;
}
div:nth-of-type(3){
background-color: #808080;
}
注意:z-index的使用前提是元素必须要有定位属性