可能会有CSS-flex布局(二)
前言
弹性盒子flex给旧世界带来的冲击和改变,旧世界指的是本人没学习flex前的对布局的视野
- 垂直居中真的方便
- 不用浮动实现三栏布局、圣杯布局
- 原来将子元素放置在想要的位置是这么的从容,如果只是定性,都不用再使用left、top了(写个筛子)
垂直居中
使用margin
body中就这
<div class="wrapper">
<div class="content"></div>
</div>
样式如下
<style>
*{
margin:0;
padding:0;
}
.wrapper{
width:500px;
height: 400px;
display:flex;
background-color: #f0f;
margin:auto;
}
.content{
width:300px;
height: 200px;
margin:auto;
background-color: #0ff;
}
</style>
效果图
结论:在flex布局中,子元素使用margin:auto;能做到垂直居中
父元素使用justify-content和align-items
样式改一下
*{
margin:0;
padding:0;
}
.wrapper{
width:500px;
height: 400px;
display:flex;
background-color: #f0f;
margin:auto;
justify-content: center;
align-items: center;
}
.content{
width:300px;
height: 200px;
/* margin:auto; */
background-color: #0ff;
}
加上justify-content: center;align-items: center;去掉子组件的margin:auto;效果看上去一样
如果你想让wrapper这个div居中到视图
效果像这样
当然可以用定位,然后left:50%;top:50%;transform:translate(-50%,-50%)的方式
这里给出其他的,关于flex的方法居中:
- wrapper在body中,如果将body设置为flex呢
- body设置为flex貌似还没达到效果,查看body高度为wrapper高度,所以现在需要给body手动设置高度为一个视图的高度
css代码如下
<style>
*{
margin:0;
padding:0;
}
body{
display:flex;
height:100vh;
}
.wrapper{
width:500px;
height: 400px;
display:flex;
background-color: #f0f;
margin:auto;
justify-content: center;
align-items: center;
}
.content{
width:300px;
height: 200px;
/* margin:auto; */
background-color: #0ff;
}
</style>
圣杯布局
body中的内容
<body>
<div class="wrapper">
<header>header</header>
<main>
<div class="left">left</div>
<div class="content">content</div>
<div class="right">right</div>
</main>
<footer>footer</footer>
</div>
</body>
css样式说明
- header和footer高度设为10%,不可压缩,不可拉伸
- main区域自动占据一个视高其他空白部分,撑满
- main区域left和right宽度设为10%,不可压缩,不可拉伸
- content区域自动占据中心其他空白部分,撑满
<style>
*{
margin:0;
padding:0;
font-size:25px;
}
.wrapper{
width:100%;
height: 100vh;
border: 1px solid black;
box-sizing: border-box;
display:flex;
flex-direction: column;
}
header,footer{
flex:0 0 10%;
border: 1px solid black;
box-sizing: border-box;
}
main{
flex:1 1 auto;
display:flex;
border: 1px solid black;
box-sizing: border-box;
}
main .left,.right{
flex:0 0 10%;
}
main .content{
flex:1 1 auto;
border: 1px solid black;
box-sizing: border-box;
}
</style>
写个筛子
内容加载失败