HTML定位——绝对定位和相对定位、固定定位
一,HTML中为什么需要定位?
1、浮动可以让多个块级盒子一行没有缝隙排列显示,经常用于横向排列盒子
2、定位则是可以让盒子自由的在某个盒子内移动位置或者固定屏幕中某个位置,并且可以压住其他盒子
二,定位
1.定位的组成
定位=定位模式+边偏移
定位模式:定位模式用于指定一个元素在文档中的定位方式。
边偏移:边偏移则决定了该元素的最终位置。
2,绝对定位
- 绝对定位指的是通过规定HTML元素在水平和垂直方向上的位置来固定元素,基于绝对定位的元素不会占据空间。
- 绝对定位的位置声明是相对于已定位的并且包含关系最近的祖先元素。如果当前需要被定为的元素没有已定位的祖先元素作为参考值,则相对于整个网页。
代码展示:
<style> .big { width: 900px; height: 600px; background-color: black; position: relative; } .box4 { width: 150px; height: 100px; background-color: red; position: absolute; top: 150px; left: 200px; } </style> <body> <div class="big"> <div class="box4"></div> </div>
效果图如下:
编辑
3、相对定位
- 相对定位与绝对定位的区别在于它的参照点不是左上角的原点,而是该元素本身原先的起点位置。并且即使该元素偏移到了新的位置,也仍然从原始的起点处占据空间。
-
<style> .wrap { width: 900px; height: 600px; background-color: black; position: relative; } .box1 { width: 150px; height: 100px; background-color: aqua; position: relative; left: 100px; top: 10px; } .box2 { width: 150px; height: 100px; background-color: antiquewhite; /* position: relative; */ left: 130px; bottom: 50px; } .box3 { width: 150px; height: 100px; background-color: olivedrab; /* position: relative; */ left: 170px; bottom: 100px; } .box4 { width: 150px; height: 100px; background-color: lightcoral; position: absolute; top: 150px; left: 200px; } .box6 { width: 150px; height: 100px; background-color: rgb(27, 173, 83); } </style> <body> <div class="wrap"> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> <div class="box4"></div> <div class="box5"></div> <div class="box6"></div> </div> </body>
-
效果图如下:
编辑
3、固定定位
position:fixed;
固定定位永远都会相对于浏览器窗口进行定位,固定定位会固定在浏览器的某个位置,不会随滚动条滚动。最常用的就是电脑里面是不是弹出的小广告,如果你不差掉它,当时滑动鼠标查看网页时,小广告一直会在那里,还有常用的就是网站或者APP的导航栏和底部的选择栏。
4,静态定位 (默认)
选择器 { position:static;}
5、粘性定位 选择器 {position:sticky;}
三、定位的扩展
1、绝对定位盒子的居中算法
加了绝对定位i的盒子不能通过 margin:0 auto;水平居中,但是可以通过以下计算方法实现水平和垂直居中。
(1)left:50%; :让盒子的左侧移动到父级元素的水平中心位置。
(2)margin-left : -100px; : 让盒子向左移动自身宽度的一半。
2、定位的特殊性
绝对定位和固定定位也和浮动类似。
(1)行内元素添加绝对或者固定定位,可以直接设置高度和宽度。
(2)块级元素添加绝对或者固定定位,如果不给宽度或者高度,默认大小是内容的大小。
结语;今天的分享就到这了,有什么问题请私信,谢谢。
#哔哩哔哩实习#