浮动布局比较灵活,但是不容易控制。而定位布局的出现,使得用户精准定位页面中的任意元素成为可能。
定位布局共有4种方式,如下表
属性值 | 说明 |
fixed | 固定定位 |
relative | 相对定位 |
absolute | 绝对定位 |
static | 静态定位(默认值) |
fixed
固定定位:指的是被固定的元素不会随着滚动条的拖动而改变位置。
“position:fixed;”是结合top、bottom、left和right这4个属性一起使用的。其中,先使用“position:fixed”让元素成为固定定位元素,接着使用top、bottom、left和right这4个属性来设置元素相对浏览器的位置。
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>固定定位title>
<style type="text/css">
.first{
width: 120px;
height: 1600px;
border: 1px solid gray;
background-color: #b7f1b7;
}
.second{
position: fixed;
top: 50px;
left: 160px;
width: 150px;
height: 100px;
border: 1px solid silver;
background-color:#b7f1b7;
}
style>
<body>
<div class="first">无定位的div元素div>
<div class="second">固定定位的div元素div>
body>
html>
relative
相对定位:指的是该元素的位置是相对于它的原始位置计算而来的。
注意,在默认情况下,固定定位元素的位置是相对浏览器而言的,而相对定位元素的位置是相对于原始位置而言的。
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>相对定位title>
<style type="text/css">
.king{
margin-top: 30px;
margin-left: 30px;
border: 1px solid silver;
background-color: skyblue;
width: 40%;
}
.king div{
width: 100px;
height: 60px;
margin: 10px;
background-color: snow;
color: black;
border: 1px solid black;
}
.three{
position: relative;
top: 20px;
left: 50px;
}
style>
<body>
<div class="king">
<div class="one">刘德华div>
<div class="two">张学友div>
<div class="three">郭富城div>
<div class="four">黎明div>
div>
body>
html>
原来位置图片
相对移动图片
top和left是相对于该元素的原始位置而言的。
absolute
使用“position:absolute;”来实现绝对定位。
一个元素变成了绝对定位元素,这个元素就完全脱离文档流了,绝对定位元素的前面或后面的元素会认为这个元素并不存在,此时这个元素浮于其他元素上面,已经完全独立出来了。
默认情况下,固定定位和绝对定位的位置是相对于浏览器而言的,而相对定位的位置是相对于原始位置而言的。
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>绝对定位title>
<style type="text/css">
.king{
padding: 15px;
border: 1px solid silver;
background-color: skyblue;
width: 30%;
}
.king div{
padding: 10px;
}
.one{
background-color: chartreuse;
}
.two{
background-color: cyan;
position: absolute;
top: 20px;
right: 40px;
}
.three{
background-color: darkred;
}
.four{
background-color: dimgrey;
}
style>
<body>
<div class="king">
<div class="one">刘德华div>
<div class="two">张学友div>
<div class="three">郭富城div>
<div class="four">黎明div>
div>
body>
html>
从这个例子可以看出,绝对定位元素的top和right是相对于浏览器而言的。
static
在默认情况下,元素没有指定position属性时,这个元素就是静态定位的。也就是说,元素position属性的默认值是static。
在CSS入门中,我们只需要掌握固定定位、相对定位和绝对定位3种就可以了,静态定位了解一下就行。
本节主要学习了定位布局,最后对其总结。
- 固定定位:fixed
- 相对定位:relative
- 绝对定位:absolute
- 静态定位:static