妙味云课堂之css:定位与层级

本文详细解析了CSS中的四种定位方式:相对定位、绝对定位、固定定位及它们的特点与应用场景。介绍了定位元素的位置控制与层级关系,并通过示例代码帮助理解。

一. 相对定位position:relative;

以自身为基准点进行定位。

a、不影响元素本身的特性;
b、不使元素脱离文档流;
c、如果没有定位偏移量,对元素本身没有任何影响;


二. 绝对定位position:absolute;

a、使元素完全脱离文档流;
b、使内嵌标签支持宽高;
c、块属性标签内容撑开宽度;
d、如果有定位父级相对于定位父级发生偏移,没有定位父级相对于body发生偏移;
e、相对定位一般都是配合绝对定位元素使用;

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
div{font-size:20px;}
body{border:1px solid black;}
.box1{width:300px;height:300px; background:red; position:relative;}
.box2{width:200px;height:200px;background:blue;}
.box3{width:100px;height:100px;background:green; position:absolute;right:0;bottom:0;}
</style>
</head>
<body>
<div class="box1"><!-- 定位父级(干爹) -->
    <div class="box2"><!-- 结构父级(亲爹) -->
        <div class="box3"></div><!-- 绝对定位元素(儿子) -->
    </div>
</div>
</body>
</html>

三. 固定定位

与绝对定位的特性基本一致,差别是始终相对整个文档进行定位;
问题:IE6不支持固定定位;

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
body{height:1500px;}
.box1{width:500px;height:100px; background:red; position:absolute;right:0;bottom:0;}
.box2{width:300px;height:300px;background:blue;position:fixed;right:0;bottom:0;}
</style>
</head>
<body>
<div class="box1">position:absolute;绝对定位</div>
<div style="width:200px; height:200px;border:5px solid black; position:relative;">
	<span class="box2">position:fixed; 固定定位(始终在右下角)</span>
</div>
</body>
</html>

四. 定位元素位置控制

top / right / bottom / left 定位元素偏移量


五.定位元素层级

默认后者层级高于前者

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>范例</title>
<style>
div{font-size:20px;}
.box1{width:100px;height:100px; background:red; position:absolute; z-index:1;}
.box2{width:200px;height:200px;background:blue; position:relative;}
.box3{width:100px;height:100px;background:green;}
</style>
</head>
<body>
	<div class="box1">div1</div>
	<div class="box2">div2</div>
	<div class="box3">div3</div>
</body>
</html>


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值