定位布局
定位布局就是允许从正常的文档流布局中取出元素, 将它放在另一个元素的上面,或者始终保持在浏览器视窗内的同一位置。
前提
文档流
-
元素:
万物皆盒: 围绕元素内容添加任何内边距、边界和外边距.
默认情况下,块级元素的内容宽度是其父元素的宽度的100%,并且与其内容一样高。
内联元素高宽与他们的内容高宽一样。无法设置尺寸, 因为它只是块级元素的一个内容, 除非添加 display: block 将它变成块元素. -
布局:
- 元素之间的交互. 正常的布局流 – 块级元素宽度百分百, 按顺序从上往下垂直排列. 内联元素会出现在同一行上, 溢出时会移动到下一行.
- 两个相邻块级元素的外边距接触, 保留大的, 这叫外边距折叠.
定位
作用: 创建一个浮动在页面其他部分顶部的UI元素,并且/或者始终停留在浏览器窗口内的相同位置.
静态定位 – 是文档的元素默认状态
<style>
.positioned {
position: static;
background: yellow;
}
</style>
相对定位 relative
相对于正常布局所在位置,或者说是对外边框的外边框进行设置
使用 top, bottom, left, right 属性定位 (单位任意) :
<style>
.positioned {
position: relative;
top: 30px;
left: 30px;
background: yellow;
}
</style>
绝对定位
子:absolute
父:relative;
在所有的父元素都是默认定位的情况下,他们的position属性都是static。那么绝对定位就是根据浏览器视口定位的. 如果把父元素设置为relative, 那么子元素的绝对定位就是根据这个父元素来定位的了.
独立于其他元素,独立一层.
margin 会影响定位.
绝对定位可以创建不干扰页面上其他元素的位置的隔离的UI功能 。例如,弹出信息框和控制菜单;翻转面板;可以在页面上的任何地方拖放的UI功能……
<style>
.positioned {
margin: 0;
position: absolute;
top: 0;
left: 0;
background: yellow;
}
</style>
<style>
.box {
width: 900px;
height: 900px;
margin: 0 auto;
background-color: aquamarine;
}
.positioned {
margin: 0;
position: absolute;
top: 0;
left: 0;
background: yellow;
}
</style>
<body>
<h1>正常文档流布局 -> 绝对定位</h1>
<div class="box">
<p class="positioned">I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
</div>
<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
</body>
由以上两个例子可以看出绝对布局时根据是根据body,或html.
经
<style>
body {
margin: 10px;
width: 500px;
padding: 10px;
}
</style>
证实绝对定位是根据html根元素 (窗口) 定位的.
z-index
绝对定位时, 元素重叠后, 由 z-index 确定谁在上方 – 相当于z轴.
没有单位.
固定定位 – fixed
- 与绝对定位的工作方式完全相同
- 区别:绝对定位固定元素是相对于 元素或其最近的定位祖先,而固定定位固定元素则是相对于浏览器视口本身。
可以用作 持久导航菜单
<style>
h1 {
position: fixed;
top: 0;
}
</style>
一直固定在指定位置.
黏性布局 – sticky
<style>
/* 黏性布局 sticky */
.sticky {
position: sticky;
top: 0;
}
</style>
在正常布局流的原位置, 当页面滚动时,到达指定位置后静止不动.
网页实例
下一节: 前端之多列布局