Flex实现水平垂直居中
flex-direction决定主轴的方向:row|row-reverse|column|column-reverse
justify-content决定主轴的对齐方式:flex-start|flex-end|center|space-between|space-around
align-items决定交叉轴的对齐方式:flex-start|flex-end|center|baseline|stretch
.box{
display: flex;
justify-content: center;
align-items: center;
border: 1px solid black;
width:500px;
height:500px;
}
实现效果:
以前写导航栏的时候,总是用float或display:inline-block实现,但是这两种方法都会有各种问题,比如浮动会影响父元素以及兄弟元素的样式,需要清除浮动,现在用flex会很方便,并且是弹性布局。
- 音乐
- 旅游
- 电影
- 综艺
ul{
display: flex;
}
li{
flex:1;
text-align: center;
line-height: 100px;
list-style: none;
background: green;
border-right: 1px solid grey;
}
实现效果:
第一行
说明1 说明2
.box{
display: flex;
justify-content: space-between;
width: 350px;
height: 150px;
border: 1px solid grey;
}
.left{
width: 100px;
height: 100px;
background: grey;
}
.right{
width: 150px;
height: 100px;
}
实现效果:
1/4
1/4
1/4
1/4
.demo{
display: flex;
}
.item{
flex: 1;
background: green;
border-right:1px solid grey;
line-height: 100px;
}
实现效果:
auto
1/2
auto
auto
.demo{
display: flex;
}
.item{
flex: 1;
background: green;
border-right:1px solid grey;
line-height: 100px;
color: #fff;
text-align: center;
}
.item2{
flex: 0 0 50%;
}
实现效果:
圣杯布局指的是一种最常见的网站布局。页面从上到下,分成三部分:头部(header),躯干(body),尾部(footer)。
其中躯干又水平分成三栏:从左到右为:导航、主栏、副栏。
头部
left
center
right
.demo{
display: flex;
flex-direction: column;
}
.demo div{
flex: 1;
}
.body{
display: flex;
}
.header, .footer{
background: grey;
line-height: 80px;
text-align: center;
}
.left, .right{
background: pink;
line-height: 200px;
text-align: center;
}
.header,.footer,.left,.right{
flex: 0 0 20%!important;
}
实现效果:
双飞翼布局,就是两端固定宽高,中间自适应的三栏布局。
#left
#center
#right
body {
min-width: 550px;
}
#container{
display: flex;
justify-content: center;
align-items: flex-start;
}
.column{
height: 200px;
color:white;
}
#center{
flex-grow: 1;
background-color: black;
}
#left{
flex-basis: 200px;
background-color: red;
}
#right{
flex-basis: 200px;
background-color: blue;
}
实现效果:
页面会经常用到固定的底栏,但是当页面内容过少时,footer会到页面中间,下面用flex来解决:
这是主要内容
.demo{
display: flex;
flex-direction: column;
width: 300px;
height: 200px;
}
.main{
flex: 1;
background: pink;
}
.footer{
width: 100%;
height: 30px;
background: grey;
}
实现效果: