Css元素位置 position的位置有两种,一种是绝对路径,一种是相对路径。
1、绝对路径的十字
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>绝对定位</title>
<style >
.box {
width: 600px;
height: 600px;
/*background-color: wheat;*/
/*定位父级必须设置定位属性*/
position: relative;
}
.box1 {
width: 200px;
height: 200px;
background-color: lightblue;
/*绝对定位会脱离文档流*/
position: absolute;
top:0;
left: 200px;
}
.box2 {
width: 200px;
height: 200px;
background-color: lightgreen;
position: absolute;
top:200px;
left: 0;
}
.box3 {
width: 200px;
height: 200px;
background-color: lightcoral;
position: absolute;
top:200px;
left: 400px;
}
.box4 {
width: 200px;
height: 200px;
background-color: lightgray;
position: absolute;
top:400px;
left: 200px;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例
2、相对路径的十字
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>相对定位</title>
<style >
.box1 {
width: 200px;
height: 200px;
background-color: lightblue;
position: relative;
left: 200px;
}
.box2 {
width: 200px;
height: 200px;
background-color: lightgreen; /*相对定位,相对自身定位*/
/*position: relative;
top: 20px;
left: 50px;*/
}
.box3 {
width: 200px;
height: 200px;
background-color: lightcoral;
position: relative;
left: 400px;
top: -200px;
}
.box4 {
width: 200px;
height: 200px;
background-color: lightgray;
position: relative;
left:200px;
top:-200px;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</body>
</html>点击 "运行实例" 按钮查看在线实例
总结:绝对路径会脱离文件流,如果不设置指定的位置,后面的图形会覆盖前面的图形。
绝对路径的起始位置(0,0)就是左上角。top XX px 意思就是距离左上角向下XX像素,如果要往上则前面加负号。
left XX px 就是新的位置往右移动XX像素。
相对路径的top XX px 就是原来的位置就是(0,0),两者的区别在于原点定义不同,top 和left的对图形的移动方向是一样的。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号