一个网站页面中会存在很多的内容,如何,将这些内容根据自己的需求合理的布局到页面中呢?我们可以通过css中的静态定位【 static】相对定位 【relative】绝对定位 【absolute】固定定位【 fixed】粘性定位 【sticky】等方式来实现该需求,下面济南网站建设小编http://news.hcsw666.com/就通过一个小案例,为大家介绍各种定位方式具体使用方法,有需要的朋友可以过来参考一下。
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS五种定位 综合案例</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
/* 把页面撑高,方便测试滚动、粘性、固定定位 */
height: 2000px;
padding: 20px;
background: #f4f4f4;
}
.box-wrap {
width: 800px;
margin: 0 auto;
border: 2px solid #666;
padding: 20px;
position: relative; /* 给绝对定位做父级参照 */
}
.item {
width: 120px;
height: 80px;
line-height: 80px;
text-align: center;
color: #fff;
border-radius: 6px;
margin: 10px 0;
}
/* 1. 静态定位 static 默认值 */
.static-box {
background: #666;
position: static;
/* top/left 对static无效 */
top: 50px;
left: 50px;
}
/* 2. 相对定位 relative */
.relative-box {
background: #2196F3;
position: relative;
top: 20px;
left: 30px;
}
/* 3. 绝对定位 absolute 以最近已定位父级为参照 */
.absolute-box {
background: #f44336;
position: absolute;
top: 20px;
right: 20px;
}
/* 4. 固定定位 fixed 相对于浏览器窗口 */
.fixed-box {
background: #4CAF50;
position: fixed;
right: 20px;
bottom: 80px;
}
/* 5. 粘性定位 sticky 滚动到阈值固定,否则正常流动 */
.sticky-box {
background: #ff9800;
position: sticky;
top: 0;
}
</style>
</head>
<body>
<!-- 粘性导航,往下滚动会固定在顶部 -->
<div class="item sticky-box">粘性定位</div>
<div class="box-wrap">
<div class="item static-box">静态定位</div>
<div class="item relative-box">相对定位</div>
<div class="item absolute-box">绝对定位</div>
</div>
<!-- 固定在浏览器右下角 -->
<div class="item fixed-box">固定定位</div>
</body>
</html>
评论