一篇代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css 之 position 定位</title>
</head>
<body>
<div class="bigbox" bg-coolGray>
<div class="box"> box
<div class="cl1">1static</div>
<div class="cl2">2static float</div>
<div class="cl3">3relative</div>
<div class="cl4">4absolute</div>
<div class="cl5">5fixed</div>
<div class="cl6" >sticky6</div>
<div class="cl7" >sticky7</div>
</div>
</div>
</body>
<style>
body {
width: 100vw;
height: 200vh;
}
div {
//display: inline-block;
border: 1px solid black;
position: relative;
width: 100px;
height: 100px;
}
.bigbox {
position: relative;
margin-top: 100px;
top: 100px;
border: 1px solid greenyellow !important;
width: 100%;
height: 200vh;
}
.box {
position: static;
margin: 100px;
//top: 100px;
border: 1px solid red !important;
width: auto;
height: auto;
}
// margin-top 会撑大父级容器的尺寸了top 只会进行位移 不会改变父级元素的尺寸;
.cl1 {
//background-color: red;
position: static;
}
.cl2 {
// 由此观之: float 和 top right位移无关
//background-color: blue;
position: static;
float: right;
right: 80px;
}
.cl3 {
background-color: green;
position: relative;
right: 20px;
// relative top left 位移是相对于父级容器来变动
}
.cl4 {
// absolute 在元素之内的;
//background-color: green;
position: absolute;
top: 2px;
right: 100px;
//right:200px //该属性不生效 需要设置定宽才能生效
//flot:right;
//margin:300px;
// absolute 是相对于最近一个不是static 定位的元素位移的. // 观察bigbox 定位可知
// absolute 如果没有设置 top 等位移 会跟在正常流之后 但是不占用正常流的空间;
}
.cl5 {
// fixed 在元素之外相对于视窗定位
//background-color: green;
position: fixed;
top:10px; left : 10px; // 如果不进行定位则是相对于父级之内 否则 fixed 在元素之外相对于视窗定位进行位移
// basolute fixed 都不会占用父级空间;即不会影响父级的宽度;
// 同时 如果不进行位移定位的话
}
.cl6 {
border:red solid 1px;
background-color:goldenrod;
position: sticky;
top: 0px;
left: 20px;
z-index: 10000;
}
.cl7 {
//background-color: red;
position: sticky;
top: 20px;
left: 20px;
height: 300px;
}
// 综上所属:
// 元素的position 定位和便宜量配合使用会表现出不同的结果;
// 首先是正常文档流 static relative;
// static 元素不会偏移 即 top:10px 无效;
// relative 元素会偏移 top:10px;
// 然后是相对定位 absolute fixed;
//如果没有设置偏移
// absolute 和 fixed 都不会占用父级空间; 但是absolute 会默认出现在正常文档流的位置; 和后续的内容堆叠;
// fixed 则出现在window的中间位置;
// 如果设置了偏移量 absolute 是相对于最近的非static父级进行定位; fixed 是相对于视窗进行定位;
// 然后是粘性定位 sticky;
// 粘性定位是属于 父级元素的; 但是设置偏移量后 会相对于window进行固定, 直至父级窗口消失 或则说 直至移动到父级边界;
// todo float 和 relative 的位移是相对于原来位置的偏移; absolute和 fixed 则是距离边界的距离;
/* // sticky 定位 表现出一种类似 relative fixed的定位状态( 这种fixed 不是相对于窗口而是相对于父级容器)
// 当未设置偏移量 top 时 sticky 元素定位表现和 relative 相同;
// 当 设置便宜量时; top 10px 当元素距离窗口 顶部距离小于10px时 会固定在顶部;
// 而父级元素继续滚动 sticky 的元素位移到父级容器的顶部时 又会和父级元素一起消失在窗口;*/
//float 和 top right位移无关
</style>
</html>
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 liudongsir's blog!
评论
GiscusGitalk