定位
定位的基本思想很简单,允许元素相对某些元素随意更改位置
- 通过使用 position 属性,我们可以选择 4 种不同类型的定位
- position属性是把元素放置到一个静态的、相对的、绝对的、或固定的位置中
- position属性的四个值分别对应static、relative、absolute、fixed
- static 静态定位(默认值)
- relative 相对定位
- absolute 绝对定位
- fixed 固定定位
- left、right、top、bottom可以设置定位的位置单位
- 单位为 px 或 百分比都可以
- left 和 right 同时设置时只有left有效
- top 和bottom一起设置时只有top有效
记忆方法:bottom 和 left按照xy轴记忆,其他两个相反!!!!!
相对定位
- 没有脱离文档流,位置还在
- 层级高于普通文档流
- 给绝对定位的元素做参照物
-
绝对定位
脱离文档流
- 层级高于普通文档流的层级
- 绝对定位的元素在设置参照物的时候,必须是包含关系的上级元素
- 浏览器在寻找参照物的时候是按照
就近原则
进行查找,如果都没有设置,那它的参照物就是视口(暂时这么记) - 原本宽度可以继承,但是定位的元素,宽度不再继承了,是由自身内容决定的。如果是行内元素,定位之后,宽、高也可以起作用。
- 如果给绝对定位元素的宽度设置百分比的时候,那它是相对你参照物来说的,并不是父级。
绝对定位的参照物:position:relative或者position:absolute、position:fixed ,只要是三者之一即可。
固定定位
面试题:如何让一个元素在整个屏幕或者是一个盒子中水平垂直居中
让这个元素position:absolute;
- left:50%;top:50%;
- margin-left:负的盒子宽的一半;
- margin-top:负的盒子高度的一半
<style>
.box{
width:200px;
height:200px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
</style>
精灵图
在做项目的时候,有时候咱们为了优化,减少http请求,会把多张图片合并到一张图片上面,这种图就是“精灵图”,也称“雪碧图”。(只针对小图)
精灵图的原理:通过改变background-position。
再记住一点,在写精灵图的时候,background-position的x轴,y轴的值一定的负的。
qq空间的雪碧图
https://qzonestyle.gtimg.cn/aoi/sprite/icenter.32-yoo2020713161005.png
1.盒子要和图片一样大小
2.给这个盒子设置背景图
3.通过background-position控制背景图的位置
字体图标讲解
iconfont官网:https://www.iconfont.cn/
ps切图讲解
作业
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>畅言</title>
<link rel="stylesheet" href="./reset.css">
<style>
.outer{
width: 500px;
height: 300px;
border: 1px solid #009ff2;
border-radius: 20px;
margin: 100px auto;
position: relative;
}
.login{
width: 80px;
height: 80px;
border-radius: 50%;
background-color: #fff;
position: absolute;
left: 30px;
top: -57px;
border: 1px solid #009ff2;
}
.login_in{
width: 50px;
height: 50px;
margin: 15px;
border-radius: 50%;
line-height: 50px;
text-align: center;
font-size: 14px;
color: #009ff2;
border: 1px solid #009ff2;
position: relative;
z-index: 2;
}
.mask{
width: 82px;
height: 57px;
background-color: #fff;
position: absolute;
left: 30px;
top: -58px;
}
</style>
</head>
<body>
<div class="outer">
<div class="login">
<div class="login_in">登录</div>
</div>
<div class="mask"></div>
</div>
</body>
</html>