0
点赞
收藏
分享

微信扫一扫

HTML+CSS基础知识(5)相对定位、绝对定位、固定定位


文章目录

  • ​​1、相对定位​​
  • ​​1.1 代码​​
  • ​​1.2 测试结果​​
  • ​​2、绝对定位​​
  • ​​2.1 代码​​
  • ​​2.2 测试​​
  • ​​3、固定定位​​
  • ​​3.1 代码​​
  • ​​3.2 测试结果​​

1、相对定位

1.1 代码

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>相对定位</title>
<style type="text/css">.box1{
width: 200px;
height: 200px;
background-color: red;
}

.box2{
width: 200px;
height: 200px;
background-color: green;
position: relative;
left: 150px;
top:200px;

}

/*
定位:
将指定的元素放到指定的位置
通过position属性来设置元素的定位

可选值:
static:默认值,元素没有开启定位
relative:相对定位 1、 相对的是自身的位置 2、相对位置的元素不会脱离文档流。
3、移动前的位置还会保留 4、会让元素提高一个层级,会遮盖另外一元素

absolute:绝对定位
fixed:固定定位

可通过left right top bottom 四个属性设置元素的偏移量
*/

.box3{
width: 200px;
height: 200px;
background-color: yellow;
}</style>
</head>

<body>
<!-- div.box$*3 -->
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>

</body>

</html>

1.2 测试结果

HTML+CSS基础知识(5)相对定位、绝对定位、固定定位_html5

2、绝对定位

2.1 代码

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>绝对定位</title>
<style type="text/css">.box1{
width: 200px;
height: 200px;
background-color: red;
}

.box2{
width: 200px;
height: 200px;
background-color: green;

/* 绝对定位:
1、会让元素脱离文档流
2、如果不设置偏移量,元素的位置不发生变化
3、相对于离他最近的开启了定位的祖先元素进行定位的。
如果所有的祖先元素都没有开启定位,则会相对于浏览器窗口进行定位
4、提升一个层级
5、改变元素的性质,行内元素变成块元素,块元素的高度和宽度都被内容打开

*/
position: absolute;
left: 400px;

}


.box3{
width: 400px;
height: 400px;
background-color: yellow;
position: relative;
}

.box4{
width: 200px;
height: 200px;
background-color: plum;
position: absolute;
top: 50px;
left: 50px;
}</style>
</head>

<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3">
<div class="box4"></div>
</div>

</body>

</html>

2.2 测试

HTML+CSS基础知识(5)相对定位、绝对定位、固定定位_绝对定位_02

3、固定定位

3.1 代码

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>固定定位</title>
<style type="text/css">.box1 {
width: 200px;
height: 200px;
background-color: red;
}

.box2 {
width: 200px;
height: 200px;
background-color: green;

/*
固定定位:
也是一种绝对定位,大部分特点和绝对定位一样

不同的是:
固定定位永远都会相对于浏览器窗口进行定位
固定定位会固定在浏览器窗口某个位置,不会随滚动条滚动

*/
position: fixed;
left:0px;
top:0px;


}



.box3 {
width: 200px;
height: 200px;
background-color: yellow;
}</style>
</head>

<body>
<!-- div.box$*3 -->
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>

</body>

</html>

3.2 测试结果

HTML+CSS基础知识(5)相对定位、绝对定位、固定定位_html_03


举报

相关推荐

0 条评论