之前都是看网上的一些教程,看完以后都觉得懂了,但是实际自己用的时候发现又是没有搞懂,这次自己弄了个示例,自己研究,终于将这个知识点搞明白了,所以无论是什么知识点不要认为简单就不去实际操作,自己操作一遍可以抵得上好几遍的看教程
正文:首先自己做一个盒模型,简单点就行,主要是自己看得懂
<!DOCTYPE html>
<html>
<head>
<title>定位</title>
<style type="text/css">
* { margin: 0; padding:0;}
.ex1{ width: 50px; height: 50px; background: red;}
.ex2{ width: 50px; height: 50px; background: blue;}
.ex3{ width: 50px; height: 50px; background: green;}
.content{ width: 300px; height: 300px; border: 1px solid;margin: 50px auto;}
</style>
</head>
<body>
<div class="content">
<div class="ex1">
</div>
<div class="ex2">
</div>
<div class="ex3">
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>定位</title>
<style type="text/css">
* { margin: 0; padding:0;}
.ex1{ width: 50px; height: 50px; background: red;}
.ex2{ width: 50px; height: 50px; background: blue;}
.ex3{ width: 50px; height: 50px; background: green;position: absolute; top: 50px; left: 50px;}
.content{ width: 300px; height: 300px; border: 1px solid;margin: 50px auto;;}
</style>
</head>
<body>
<div class="content">
<div class="ex1">
</div>
<div class="ex2">
</div>
<div class="ex3">
</div>
</div>
</body>
</html>
因为ex3的父级元素没有定位,所以ex3绝对定位之后直接跑出了content的范围
<!DOCTYPE html>
<html>
<head>
<title>定位</title>
<style type="text/css">
* { margin: 0; padding:0;}
.ex1{ width: 50px; height: 50px; background: red;}
.ex2{ width: 50px; height: 50px; background: blue;}
.ex3{ width: 50px; height: 50px; background: green; position: absolute; top: 50px; left: 50px}
.content{ width: 300px; height: 300px; border: 1px solid;margin: 50px auto;position: relative;}
</style>
</head>
<body>
<div class="content">
<div class="ex1">
</div>
<div class="ex2">
</div>
<div class="ex3">
</div>
</div>
</body>
</html>
给ex3的父级content加了一个相对定位,这样ex3就跑到了content内了
这个非常简单,你可以给ex1/2加上绝对定位/相对定位等等都试试看,如果改完代码和自己实际想要的结果一样,那恭喜你定位你已经掌握了