定位
Basic
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic document flow</title>
<style>
body {
width: 500px;
margin: 0 auto;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Basic document flow</h1>
<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
<p>By default we span 100% of the width of our parent element, and our height is as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="long.jpg"></p>
</body>
</html>
1、静态定位
静态定位是每个元素获取的默认值。
2、相对定位
position: relative;
top、bottom、left和right来精确指定要将定位元素移动到的位置。
注意: 这些属性的值可以采用逻辑上期望的任何单位 ——px,mm,rems,%等。
3、绝对定位
position: absolute;
top、bottom、left和right来精确指定元素应距离每个包含元素的边的距离。
注意: margin仍会影响定位的元素。 然而margin collapsing不会。
4、定位上下文
子绝父相
所有的父元素默认情况下position属性都是static。
通过设置其中一个父元素的定位属性 —— 也就是包含绝对定位元素的那个元素。
在父元素加入以下代码:
position: relative;
top、bottom、left和right来精确指定元素应距离父元素的边的距离。
5、z-index
更改堆叠顺序可以使用z-index属性。
z-index越大,元素就在越前面,反之,就越后面。
.positioned {
position: absolute;
background: yellow;
top: 30px;
left: 30px;
z-index: 2;
}
p:nth-of-type(1) {
position: absolute;
background: lime;
top: 10px;
right: 30px;
z-index: 1;
}
类positioned将显示在第一个段落元素前面。
6、固定定位
fixed与绝对定位的工作方式完全相同,只有一个主要区别:绝对定位固定元素是相对于<html>元素或其最近的定位祖先,而固定定位固定元素则是相对于浏览器视口本身。
h1 {
position: fixed;
top: 0;
width: 500px;
margin: 0 auto;
background: white;
padding: 10px;
}
标题1将被固定,内容显示向上滚动并消失在其下。
7、position: sticky
position: sticky相对位置和固定位置的混合体,它允许被定位的元素表现得像相对定位一样,直到它滚动到某个阈值点(例如,从视口顶部起10像素)为止,此后它就变得固定了。
dt {
background-color: black;
color: white;
padding: 10px;
position: sticky;
top: 0;
left: 0;
margin: 1em 0;
}
在正常布局流中,<dt>元素将随内容滚动。当我们在<dt>元素上添加position: sticky,并将top的值设置为0,当标题滚动到视口的顶部时,支持此属性的浏览器会将标题粘贴到那个位置。随后,每个后续标题将替换前一个标题,直到它向上滚动到该位置。