CSS基础学习(定位)(六)

it2023-06-24  70

定位(Position)

一、position: static

该关键字指定元素使用正常的布局行为,即元素在文档常规流中当前的布局位置。此时 top、right、bottom、left 属性无效。

个人补充:static是position的默认值。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>change-to-flex</title> <link rel="stylesheet" href="./reset.css"> <style> .block { position: relative; top: 30px; width: 50px; height: 50px; line-height: 50px; text-align: center; border: 2px solid blue; box-sizing: border-box; } .block:nth-child(1) { border: 2px solid green; margin-left: auto; margin-right: auto; /*margin: 30px;*/ } .block:nth-child(2) { position: static; /*定位无效*/ /*border-color: red;*/ /*margin: 20px;*/ border: 2px solid red; } </style> </head> <body> <div class="block"> A </div> <div class="block"> B </div> <div class="block"> C </div> <div class="block"> D </div> </body> </html>

对 content 的 position 设定 static 后,left就失效了,而元素(content)就以正常的 normal flow 形式呈现。.

二、position: relative

MDN的描述:

该关键字下,元素先放置在未添加定位时的位置,再在不改变页面布局的前提下调整元素位置(因此会在此元素未添加定位时所在位置留下空白)。position:relative 对 table-*-group, table-row, table-column, table-cell, table-caption 元素无效。

个人理解:相对于normal flow中的原位置来定位。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>position-relative</title> <link rel="stylesheet" href="./reset.css"> <style> .block { position: relative; top: 0; left: 0; width: 80px; height: 80px; line-height: 80px; border: 2px solid black; text-align: center; float: left; z-index: 9; } .block:nth-child(2) { position: relative; top: 0; left: -50px; border-color: red; z-index: 1; } </style> </head> <body> <div class="block">A</div> <div class="block">B</div> <div class="block">C</div> </body> </html>

可以看到,元素(content1)的位置相对于其原位置进行了移动。

三、position: absolute

MDN的描述

不为元素预留空间,通过指定元素相对于最近的非 static 定位祖先元素的偏移,来确定元素位置。绝对定位的元素可以设置外边距(margin),且不会与其他边距合并。

个人理解:生成绝对定位的元素,其相对于 static 定位以外的第一个父元素进行定位,会脱离normal flow。注意:是除了static外

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS-position-static</title> <link rel="stylesheet" href="https://cdn.bootcss.com/normalize/8.0.0/normalize.css"> <style> .container{ background-color: #868686; width: 100%; height: 300px; position: absolute; left: 10px;/* 这个left没有起作用 */ top: 50px; } .content{ background-color: red; width: 100px; height: 100px; } </style> </head> <body> <div class="container"> </div> <div class="content"> </div> </body> </html>

 

因为 content 的父元素 container 没有设置 position,默认为 static,所以找到的第一个父元素是 body(<body></body>),可以看成是元素(content)相对于 body 向下移动10px。

四、position: fixed

MDN的描述

不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置。元素的位置在屏幕滚动时不会改变。打印时,元素会出现在的每页的固定位置。fixed属性会创建新的层叠上下文。当元素祖先的 transform 属性非 none 时,容器由视口改为该祖先。

个人理解:fixed相对于window固定,滚动浏览器窗口并不会使其移动,会脱离normal flow。

这里就不上图了,看一下代码或者自己动手码一下就能理解。

五、position: sticky

MDN的描述

盒位置根据正常流计算(这称为正常流动中的位置),然后相对于该元素在流中的 flow root(BFC)和 containing block(最近的块级祖先元素)定位。在所有情况下(即便被定位元素为 table时),该元素定位均不对后续元素造成影响。当元素 B 被粘性定位时,后续元素的位置仍按照 B 未定位时的位置来确定。position: sticky对 table元素的效果与 position: relative 相同。

最新回复(0)