html 使用定位改变网页元素位置
子级绝对定位,父级相对定位
一 相对位置(参照自己原来所在的位置)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.sidebar{
height: 200px;
width: 300px;
background-color: red;
}
.sidebar {
position: relative;
/* left: -500px; */
/* top: 300px; */
}
</style>
</head>
<body>
<div class="sidebar">
</div>
</body>
<script>
</script>
</html>
下移(top: 300px;)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.sidebar{
height: 200px;
width: 300px;
background-color: red;
}
.sidebar {
position: relative;
/* left: -500px; */
top: 300px;
}
</style>
</head>
<body>
<div class="sidebar">
</div>
</body>
<script>
</script>
</html>
上移(top: -300px;)
右移left: 500px;
左移left: -500px;
二 绝对位置
1.脱标,不占位置,浮起
2.行内块效果,高宽生效
3.找最近的有定位祖先块元素,根据其元素设置绝对位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
position: relative;
width: 500px;
height: 500px;
bottom: 0;
left: 0;
background-color: #000;
}
.show{
position: absolute;
top:0;
right: 0;
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="show">
</div>
</div>
</body>
</html>
三 固定定位
position: fixed
场景:元素的位置在网页滚动时不会改变
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
position: fixed;
top:0;
right: 0;
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div></div>
</body>
</html>