开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情
在项目中我最常使用的布局实现方式有两种,一种是相对定位和绝对定位进行布局,一种是使用flex布局,最常用到的就是flex,大概能在项目中90%的比例,这篇主要是分享项目中常用的布局和对应的flex样式,熟练掌握了布局你会感觉开发的速度都会快很多。
这里关于flex的语法知识就不做介绍,已经有很多很好的资料,大家可以自行查找,这里给大家推荐我当时用来学习的阮一峰的两篇flex文章,写的很好,看懂了flex的基础知识应该没有什么问题。
- 垂直居中
常用于登陆页,不定高div中文字居中等
html代码:
<div class="demo">
<div class="box"></div>
</div>
css代码:
.demo {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: gray;
}
.box {
width: 700px;
height: 500px;
background-color: red;
}
效果:
- 两栏,左侧固定,右侧自适应
常用于后台管理页面中,左侧为菜单栏,右侧内容区域自适应。
html代码:
<div class="demo">
<div class="left-box"></div>
<div class="right-box"></div>
</div>
css代码:
.demo {
width: 100vw;
height: 100vh;
display: flex;
background-color: gray;
}
.left-box {
width: 300px;
height: 100%;
background-color: red;
}
.right-box {
flex: 1;
height: 100%;
background-color: blue;
}
效果:
- 三栏,左侧和右侧固定宽度,中间区域自适应
常用于大屏可视化页面中,左右两侧为数据图表展示区域,中间为地图区域。
html代码:
<div class="demo">
<div class="left-box"></div>
<div class="right-box"></div>
</div>
css代码:
.demo {
width: 100vw;
height: 100vh;
display: flex;
background-color: gray;
}
.left-box {
width: 300px;
height: 100%;
background-color: red;
}
.right-box {
flex: 1;
height: 100%;
background-color: blue;
}
效果:
- 整体居中,其中各元素水平均匀分布
这种布局用的非常多,这里以可视化大屏开发中常用的底部导航菜单为例,导航菜单相对整个页面处于底部居中的位置,其中四个导航菜单水平均匀分布,对于每一个导航菜单也使用了flex进行图标和文字的垂直居中对齐。
html代码:
<div class="demo">
<div class="nav-box">
<div class="nav-item">
<span class="img"></span>
<span class="name">导航一</span>
</div>
<div class="nav-item">
<span class="img"></span>
<span class="name">导航二</span>
</div>
<div class="nav-item">
<span class="img"></span>
<span class="name">导航三</span>
</div>
<div class="nav-item">
<span class="img"></span>
<span class="name">导航四</span>
</div>
</div>
</div>
css代码:
.demo {
width: 100vw;
position: absolute;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
}
.nav-box {
width: 800px;
border: 2px solid red;
display: flex;
align-items: center;
justify-content: space-between;
}
.nav-item {
display: flex;
flex-direction: column;
align-items: center;
}
.img {
width: 50px;
height: 50px;
background-color: burlywood;
}
效果: