目录
01 position定位之相对定位
position:relation;
特性:
1:相对定位以元素自身的位置为基准设置位置
2:相对定位占位置
<style>
div{
width: 200px;
height: 200px;
background-color: red;
margin: 100px auto; */
/* 定位=定位模式+边偏移*/
position: relative;
top: 100px;
left: 100px;
}
</style>
02 position定位之绝对定位
position:absolute;
绝对定位 父级为标准移动位置
如果父级没有定位 绝对定位的盒子以我们文档为准
如果父级有定位 绝对定位以父级为准移动位置
03 绝对定位不占有位置
<style>
#father{
width: 500px;
height: 500px;
background-color: red;
position: relative;
}
.one{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
top:0;
left: 0;
}
.two{
width: 250px;
height: 250px;
background-color: green;
}
</style>
############################################
<div id="father">
<div class="one"></div>
<div class="two"></div>
</div>
04 子绝父相定位
<style>
.up{
width: 1000px;
height: 100px;
background-color: red;
position: relative;
}
.down{
width: 1200px;
height: 200px;
background-color: #000;
}
.up>div{
width: 40px;
height: 40px;
border-radius: 20px;
background-color: purple;
position: absolute;
}
.arr-l{
left: 0;
top:30px;
}
.arr-r{
right: 0;
top:30px;
}
</style>
####################################################
<div class="up">
<div class="arr-l"></div>
<div class="arr-r"></div>
</div>
<div class="down"></div>
05 固定定位
<style>
body{
height: 3000px;
}
.box{
width: 300px;
height: 300px;
background-color: red;
margin: 100px;
}
.box img{
/* 和父级没有任何关系 脱标*/
position: fixed;
right: 0;
bottom: 0;
}
</style>
#######################################################
<div class="box">
<img src="./01.png" alt="">
</div>
06堆叠次序
<style>
div{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
}
.one{
z-index: 10
}
.two{
top:50px;
left:50px;
background-color: green;
/* 数值越大越靠上 后面不要跟单位 只能是整数 */
z-index:2;
}
.three{
top:100px;
left:100px;
background-color: blue;
}
</style>
#########################################################
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
07 绝对定位改变display属性
块级元素 不给width 默认和父元素一样宽
行内设置宽度不生效
绝对定位可以转换(行内元素宽高生效)
浮动也可以
<style>
div{
height: 100px;
background-color: red;
}
span{
/* position: absolute; */
/* float: left; */
/* position: relative;不可以 */
position: fixed;
width: 300px;
height: 300px;
background-color: blue;
}
</style>
###################################################
<div>我是div标签</div>
<span>我是span标签</span>
<span>我是span标签</span>
08 所有居中问题的总结
横向居中
行内 行内块 文字 在块级里面横向居中
给块级元素添加text-align:center
行内文字 行内块在行内块里面横向居中
给行内块元素添加text-align:center
块级在另一个块级里面横向居中
给内部的块级加宽度(小于外部的)
同时设置margin:0 auto
纵向居中
行内 文字在块级里面纵向居中
给当前的块级+line-height=当前块级元素高度 前提是 行内和文字是单行的
行内块 在块级里面纵向居中
给当前行内块+vertical-align:middle
给外部的块级+line-height:块级的高度
不一定百分百生效
块级元素在另一个块级里面纵向居中
只能通过定位 top 50% margin-top:-自身高度的一半
绝对居中
第一种
分开横向居中+纵向居中
top:50%;margin-top:-自身高度的一半
left:50%;margin-left:-自身宽度的一半
第二种
left:0;top:0;right:0;bottom:0;
margin:auto