HTML的position属性使用
一、position的应用场景
-
position
有多个值,其中三个经常用的到分别:relative
absolute
fixed
。relative
:相对定位,相对自己当前位置进行定位,会被相邻元素影响,在子元素进行top、left等定位时候会根据父辈来参考。 -
absolute
绝对定位,相对于父级并且父级设置了relative
进行定位。如果父级没有设置relative
使用margin-top属性的时候,会让父级随之变动。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>定位</title>
</head>
<body>
<h1 style="background-color: slateblue;margin: 0;">h1标签</h1>
<!-- 被测试父辈div -->
<div class="father">
<!-- 被测试子辈div -->
<div class="son">我是子</div>
</div>
<!-- css样式 -->
<style type="text/css">
/* 设置父辈盒子的样式 */
.father {
width: 500px;
height: 500px;
background-color: aqua;
font-size: 20px;
}
/* 设置子辈盒子的样式 */
.son {
width: 100px;
height: 100px;
margin-top: 50px;
background-color: seagreen;
/* top: 200px;
left: 200px; */
}
</style>
</body>
</html>
如何解决父辈元素会被子辈的margin属性影响呢?只需要在子辈position
设置为absolute
即可。但是一般推荐搭配父辈position: relative;
来使用,并且子辈使用left、top等属性来定位。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>定位</title>
</head>
<body>
<h1 style="background-color: slateblue;margin: 0;">h1标签</h1>
<!-- 被测试div -->
<div class="father">
<div class="son">我是子</div>
</div>
<!-- css样式 -->
<style type="text/css">
/* 设置父辈盒子的样式 */
.father {
width: 500px;
height: 500px;
background-color: aqua;
font-size: 20px;
position: relative;
}
/* 设置子辈盒子的样式 */
.son {
width: 100px;
height: 100px;
background-color: seagreen;
top: 200px;
left: 200px;
position:absolute
}
</style>
</body>
</html>
-
fixed
固定定位fixed
是以当前浏览器进行定位,用多侧边栏比较多,用来跳转指定位置,侧边栏悬浮等。position:fixed
设置后,该元素不会随滚动条而滚动,会悬浮于整个页面之上。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a name="top"><b>顶部</b></a>
<div class="box"></div>
<div class="fixedBox"><a href="#top">返回顶部</a></div>
<!-- css样式 -->
<style type="text/css">
.box{
height: 2000px;
}
.fixedBox{
width: 30px;
height: 100px;
background-color: #aa0000;
position: fixed;
top: 40%;
right: 0;
}
.fixedBox a{
font-weight: bold;
color: #F0F8FF;
}
</style>
</body>
</html>