css的绝对定位

1. 绝对定位元素的祖先元素没有使用非static的属性进行定位时

此时,绝对定位元素相对与初始包含块ICB进行定位
初始包含块ICB是包含html的块,相当于html的父元素

1. html代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            border: 0;
        }
        html{
            background-color: wheat;
            width: 562px;
            height: 500px;
            position: static;
            top: 100px;
            left: 300px;
            border: 1px solid black;
            margin-top: 300px;
        }
        body{
            background-color: yellowgreen;
            border: 1px dashed red;
        }
        #wrapper{
            background-color: darkgray;
            
        }
        
        .box {
            display: inline-block;
            background-color: red;
            box-sizing: border-box;
            color: white;
            width: 100px;
            height: 100px;
            float: left;
            opacity: 0.3;
            margin: 22px;
        }
        #three{
            position: absolute;
            top: 102px;
        }
        div#test{
            background-color: darkcyan;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <div class="box" id="one">one</div>
        <div class="box" id="two">two</div>
        <div class="box" id="three">three</div>
        <div class="box" id="four">four</div>
    </div>
    <div id="test">test</div>
</body>

</html>

2.渲染效果:

在这里插入图片描述

2. 祖先元素使用非static定位时

此时,绝对定位元素相对于其最近的使用非static定位的祖先元素

下面代码时上面代码的改动处,便于对比查看:

 #wrapper{
    background-color: darkgray;
    position: relative;
 }
 
#three{
    position: absolute;
    top: 30px;
    left: 30px;
}
        

使用绝对定位的元素three 颜色块 相对于其父元素#wrapper定位
在这里插入图片描述

总结

static定位:默认定位,此时topbottomleftrightz-index无效
相对定位relative:元素不脱离文档流,不改变页面布局,相对自身的top等属性定位
绝对定位absolute:脱离文档流,改变页面布局,相对于初始包含块ICB或者使用非static定位的祖先元素
固定定位fixed:与绝对定位类似,脱离文档流,改变页面布局,相对于浏览器视口定位
粘性定位sticky:相对定位与固定定位的组合,相对于自身或浏览器视口定位

初始包含块ICB就是浏览器视口viewport,该视口宽高可变,宽高随着浏览器的放大缩小而变化

绝对定位与固定定位都相对于视口定位的条件:使用这两个定位的元素没有使用非static祖先元素,此时两种定位效果类似

续:html继承视口高度

html{
	height: 100%;   // 视口有多高, 这个height就是多高
}
body{
	height: 100%; // html有多高,这个height就是多高
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值