什么是CSS?
在Web页面设计中,HTML定义页面的结构,CSS则定义页面的样式,美化页面。 本次介绍CSS的布局技巧--定位(position)、浮动(float)。
定位(position)
position属性指定元素的定位类型,其含有五个值;元素可以使用顶部(top)、底部(bottom)、左侧(left)、右侧(right)属性定位。
- static:默认值,即没有定位,遵循正常的文档流对象,此时top、bottom、left、right、z-index均无效。
<!DOCTYPE html>
<html>
<head>
<title>示例</title>
<meta charset="utf-8" />
<style>
.static{
position: static;
border: 3px solid blue
}
</style>
</head>
<body>
<h1>Position: static</h1>
<div class="static">
这是一个静态定位的元素。
</div>
</body>
</html>
示例代码结果如下:
- relative:相对定位的定位是相对其正常位置,需注意的是移动相对定位元素,但其原本所占的空间不变,被常用来作为绝对定位元素的容器块。
<!DOCTYPE html>
<html>
<head>
<title>示例</title>
<meta charset="utf-8" />
<style>
div{
width: 300px;
height: 100px;
background-color: blue;
text-align: center;
}
.left{
position: relative;
left: -50px;
background-color: red;
}
.right{
position: relative;
left: 50px;
background-color: green;
}
</style>
</head>
<body>
<div>这是正常位置的盒</div>
<div class="left">这是相对于正常位置偏左的盒</div>
<div class="right">这是相对于正常位置偏右的盒</div>
</body>
</html>
示例代码结果如下:
红色盒子与绿色盒子的实际占用空间与外表不同,实际占用空间是正常位置的红绿盒子,在实际的应用中,relative并不好用,容易影响页面的合理排版,所以并不推荐。
- fixed:元素的位置相对于浏览器窗口来说是固定的,即使窗口滚动也不移动,一般用于导航栏。
<!DOCTYPE html>
<html>
<head>
<title>示例</title>
<meta charset="utf-8" />
<style>
nav{
background-color: aquamarine;
position: fixed;
width: 100%;
height: 30px;
}
nav > ul{
margin: 0;
padding: 0;
list-style: none;
display: flex;
justify-content: space-evenly;
font-size: 20px;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">攻略</a></li>
<li><a href="#">关于</a></li>
<li><a href="#">帮助</a></li>
</ul>
</nav>
<!-- 省略多行<p> -->
<p>示例代码</p>
</body>
</html>
示例代码结果如下:
- absolute:绝对定位元素的位置是相对最近的已定位的父元素,若没有父元素,则其位置相对于,并且绝对定位元素的位置与文档流无关,因此不占用空间,可以与其他元素重叠。可用于轮播图的左右移动按钮或右键显示菜单等等
<!DOCTYPE html>
<html>
<head>
<title>示例</title>
<meta charset="utf-8" />
<style>
.upper{
background-color: aqua;
width: 100px;
height: 100px;
position: absolute;
}
.lower{
background-color: aquamarine;
width: 200px;
height: 200px;
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="upper"></div>
<div class="lower"></div>
</body>
</html>
示例代码结果如下:
- sticky:粘性定位的元素是基于用户的滚动,在relative与fixed定位之间来回切换,其有特定阈值为top、bottom、right、left之一,只有指定四个阈值其中之一,才能是粘性定生效,否则其行为与相对定位(relative)相同。同样, 其也可用于导航栏或重要公示中。
浮动(float)
float会使元素向左或向右移动,其周围的元素会重新排列,往往用于图像,例如文章插图、多个图像有序排列。
<!DOCTYPE html>
<html>
<head>
<title>示例</title>
<meta charset="utf-8" />
<style>
.img {
float: right;
width: 100px;
height: 100px;
background-color: aquamarine;
}
</style>
</head>
<body>
<p><div class="img"></div>这是一段文</p>
</body>
</html>
示例代码结果如下: