CSS position属性用于指定一个元素在文档中的定位方式。
position属性取值
- static(默认值) 自动定位
- relative 相对定位
- absolute 绝对定位(脱离文档流)
- fixed 固定定位(脱离文档流)
要了解css定位,我们先了解一下定位元素和偏移量
定位元素
计算后position属性值为 relative, absolute, fixed 元素(换句话说,只要position的值不是static,该元素就是一个定位元素)。
偏移量
由于绝对定位和固定定位的元素会脱离文档流,所以我们需要通过偏移量来确定它的具体位置。
偏移量有四个属性:left 、 right 、 top 、 button
这四个属性每个方向选一个属性用来定位即可。
position属性详细介绍
position: static
自动定位:元素根据常规文档流定位。此时偏移量 top, right, bottom, left 属性无效。
position: relative
相对定位:相对定位的元素是在文档中的正常位置偏移给定的值,但是不影响其他元素的偏移。(因此会在此元素未添加定位时所在位置留下空白)。
html
<div class="box">
<p class="txt1"></p>
<p class="txt2"></p>
<p class="txt3"></p>
<div class="box2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam accusantium hic ad ullam ut
incidunt ipsa!
Cupiditate, recusandae consequuntur, impedit facere itaque vero aperiam fugit modi numquam optio dolore
quis.
</div>
</div>
css
.box {
width: 100%;
height: 660px;
background-color: #ccc;
}
p {
display: inline-block; /* 将p元素设置成行内块元素 */
width: 200px;
height: 200px;
margin-bottom: 20px;
background-color: aqua;
border: 1px solid;
}
.txt2 {
background-color: aquamarine;
position: relative;
top: 150px;
left: 150px;
}
.box2 {
height: 50px;
background-color: tan;
}
效果:
position: absolute
绝对定位:绝对定位的元素则脱离了文档流。在布置文档流中其它元素时,绝对定位元素不占据空间。绝对定位元素会相对于最近的祖先级定位元素进行定位。如果不存在这样的元素,则相对于body进行定位
在使用时,如果其父元素不是定位元素,我们一般会给其父元素相对定位以方便布局(子绝父相)
html
<div class="box">
<p class="txt1"></p>
<p class="txt2"></p>
<p class="txt3"></p>
<div class="box2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam accusantium hic ad ullam ut
incidunt ipsa!
Cupiditate, recusandae consequuntur, impedit facere itaque vero aperiam fugit modi numquam optio dolore
quis.
</div>
</div>
css
.box {
margin-top: 50px;
width: 100%;
height: 660px;
background-color: #ccc;
/* 给父元素相对定位 */
position: relative;
}
p {
display: inline-block; /* 将p元素设置成行内块元素 */
width: 200px;
height: 200px;
margin-bottom: 20px;
background-color: aqua;
border: 1px solid;
}
.txt2 {
background-color: aquamarine;
/* 给.txt2绝对定位 */
position: absolute;
/* 设置其相对于最近的祖先级定位元素的偏移量 */
top: 50px;
left: 50px;
}
.box2 {
height: 50px;
background-color: tan;
}
效果
position: fixed
固定定位:固定定位与绝对定位相似(会脱离文档流),但元素的包含块为 viewport 视口(相对于可视窗口进行定位)。该定位方式常用于创建在滚动屏幕时仍固定在相同位置的元素。
html
<p> <!-- 这里内容太多,请自行加入内容 --> </p>
<div class="box">
我是固定定位元素
</div>
css
.txt {
margin-bottom: 20px;
background-color: #ccc;
border: 1px solid;
text-align: center;
}
.box {
width: 100px;
height: 100px;
background-color: aqua;
/* 设置固定定位 */
position: fixed;
/* z-index: 2; */
top: 200px;
right: 50px;
}