使用css去除定位
在网页制作的过程中,经常会使用position来定位元素实现布局,那么,若想取消定位,应该怎么操作呢?
1、我们可以先使用div标签创建一个盒子,并将盒子的class命名为body,并且在.body的盒子中再创建一个div盒子以用于定位,并将其class命名为body-inside。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用css去除定位</title>
</head>
<body>
<div class="body">
<div class="body-inside">被定位的盒子</div>
</div>
</body>
</html>
2、其次,我们要先设置.body这个盒子的样式,设置盒子的宽width为300px,高height为200px,并设置background背景颜色为红色,给与其相对定位的属性 position: relative;。
<style>
.body{
width: 300px;
height: 200px;
background: red;
position: relative;
}
</style>
3、再其次,我们要设置被定位的盒子body-inside的样式,设置宽width为100px,高height为100px,设置background背景颜色为白色,并给予其绝对定位属性position: absolute;。
.body-inside{
width: 100px;
height: 100px;
background: white;
position: absolute;
left: 30px;
top: 10px;
}
4、至此,基本的样式框架已经搭建好了。
5、现在我们就需要给.body-inside这个盒子去除定位属性了。
我们可以在style中,再创建一个类名为addclass的样式,将position属性设置为static,即清除定位属性,凡是添加了该类名样式,都会清除定位。将addclass此类名添加到被定为的盒子上,以清除它的定位。
.addclass{
position: static;
}
<div class="body-inside addclass">被定位的盒子</div>
5、然后,我们可以查看一下效果。
清除前
清除后
整体代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用css去除定位</title>
</head>
<style>
.body{
width: 300px;
height: 200px;
background: red;
position: relative;
}
.body-inside{
width: 100px;
height: 100px;
background: white;
position: absolute;
left: 30px;
top: 10px;
}
.addclass{
position: static;
}
</style>
<body>
<div class="body">
<div class="body-inside addclass">被定位的盒子</div>
</div>
</body>
</html>