十八、定位
1.position 属性
- `position`属性是定位属性,用于指定一个元素在文档中的定位方式。
- top,right,bottom 和 left 属性值则决定了该元素的距离四边的位置,可以为负值。
- 开发中多用绝对长度单位 px 进行调整,如果在移动端中,可以使用 rem、vw 等单位进行调整。
- 常用取值:
- `relative` 相对定位
- `absolute` 绝对定位
- `fixed` 固定定位
2.相对定位
- 相对定位 position: relative 不脱离文档流。
- 可使用 top,right,bottom 和 left 做偏移。
- 元素相对的位置是自己本来的位置,移动不改变页面布局。
- 相对定位属性不会影响周围的布局,但会出现新的层叠顺序。
- 当四个方向值发生重合时,以 top 和 left 为优先。

3.绝对定位
- absolute 绝对定位,元素将脱离文档流,其他元素不为该元素预留空间。
- 它的移动参照为祖先元素的偏移,来确定元素位置。元素会逐层向上寻找自己的参照元素,当找到的最近一层祖先元素具有 position 属性时,该元素就会以这个祖先元素的原点为参照点。
- 可使用 top,right,bottom 和 left 做偏移。
- 当四个方向值发生重合时,以“上 top”和“左 left”为优先。
- 绝对定位的元素可以设置外边距,且不会与其他边距合并。
- 应用场景背景图中的文字和按钮,轮播图中的控制符

(1)子元素在父元素中定位

(2)子元素在父元素内居中
使用元素定位,让已知高度的子元素在父元素中上下左右居中
<style>
.baba {
width: 500px;
height: 400px;
background-color: red;
position: relative;
}
.erzi {
width: 150px;
height: 200px;
background-color: blue;
position: absolute;
left:50%;
top:50%;
margin-left: -75px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="baba">
<div class="erzi"></div>
</div>
</body>
4.固定定位
fixed 固定定位是元素,决定它的“包含块”是 html,唯一可以限定固定定为元素的就是 html 跟元素
- `position: fixed;`它到父级始终是 html
- 直接在窗口的某个位置固定
- 可使用 top,right,bottom 和 left 做偏移。
(1)居中的弹窗
固定定为,元素在父元素中居中
* {
margin: 0;
padding: 0;
}
.alertBox {
width: 300px;
height: 200px;
color: red;
background-color: #aaa;
position: fixed;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
}
(2)返回顶部元素
<style>
* {
margin: 0;
padding: 0;
}
.pic {width: 100%;}
.pic img {
width: 100%;
display: block;
}
.top {
width: 100px;
height: 100px;
border-radius: 5px;
background-color: rgba(0,0,0,0.5);
font-size: 30px;
text-align: center;
line-height: 100px;
position: fixed;
bottom: 100px;
right: 100px;
}
.top a {
color: #fff;
text-decoration: none;
}
</style>
<body>
<div class="pic">
<img src="./img/固定定位长图背景.jpg" alt="">
</div>
<div class="top">
<a href="#">TOP</a>
</div>
</body>
</html>
5.z-index
z-index 就是 z 轴的顺序,z-index 可以设置字符值,如:auto,多数情况设置整数值,可以为负值。z-index 的最大值是 21,4748,3647 (21 亿多)。跨度尽量 10 以上
(1) 层叠顺序取值
- `z-index`层叠顺序
- 直接设置没有单位的整数,可以为负值,值越大层级越高

(2) 层叠领域的准则
- 值大的在上:z-index 的值,在同一个层叠上下文领域,层叠水平值大的那一个覆盖小的。
- 后来的在上:当元素的层叠水平一致的时候,在文档流中处于后面的元素会覆盖前面的元素

<!-- 移动端固定背景,要用浏览器移动端打开 -->
<style>
.box {
width: 100%;
position: fixed;
z-index: -1;
}
</style>
<div class="box">
<img src="./img/手机背景图750x1334@2.jpeg" alt="" />
</div>
<p>Lorem*3</p>
【练习】
>背景图
>浮动布局
>定位

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./cssReset.css">
<link rel="stylesheet" href="./index.css">
<style></style>
</head>
<body>
<div class="bg">
<div class="nav-part">
<div class="center">
<ul>
<li><a href="#">HOME</a></li>
<li><a href="#">LOGIN</a></li>
<li>
<a href="#">LIST</a>
<ol>
<li>全国图鉴</li>
<li>属性介绍</li>
<li>精灵石大全</li>
<li>精灵球</li>
</ol>
</li>
<li><a href="#">CARD</a></li>
<li><a href="#">SEARCH</a></li>
</ul>
</div>
</div>
<div class="ball-part">
<div class="center">
<ul>
<li>
<img src="./img/1.png" alt="">
<a href="#">训练师登录</a>
</li>

2553

被折叠的 条评论
为什么被折叠?



