<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="container">
<div id="a1"></div>
<div id="a2"></div>
<div id="a3"></div>
</div>
<style>
#container{
border: 5px yellow solid;
height: 300px;
width: 300px;
}
#a1{
height: 100px;
width: 100px;
background-color: red;
}
#a2{
height: 100px;
width: 100px;
background-color: green;
}
#a3{
height: 100px;
width: 100px;
background-color: blue;
}
</style>
</body>
</html>
效果如图:
对a2颜色块加position定位属性:
1、fixed:生成绝对定位的标签,相对于浏览器窗口进行定位,此时元素不会随着滚动调的滑动而滑动。
#a2{
height: 100px;
width: 100px;
background-color: green;
position: fixed; /*fixed是相对于浏览器页面定位,此时该颜色块会“漂浮起来”,不会随着页面的滑动而移动。*/
bottom: 10px; /*相对于浏览器页面定位,距底部10px*/
right: 10px; /*距右边10px*/
2、relative、absolute
relative:生成相对定位的标签;
absolute:生成绝对定位的标签,相对于标签本身第一个position为非 static父元素进行定位。标签通过 “left”, “top”, “right” 以及 “bottom” 样式属性进行定位。如果该标签所在的父标签均没有设置position为非 static,则相对于浏览器窗口进行定位,但是此时元素会随着滚动调的滑动而滑动。
#container{
position: relative; /*设置container为relative*/
border: 5px yellow solid;
height: 300px;
width: 300px;
}
#a1{
position: absolute; /*a1为absolute,父类标签container设置了relative非static,这样a1就会根据container定位*/
right: 10px;
top: 10px;
height: 100px;
width: 100px;
background-color: red;
}