前言
相较于定位,浮动来说,Flex和Grid才是真正为了浏览器布局而开发的CSS布局系统。两列布局是我们经常使用的一种布局
1 – 经典两列布局
效果如图
<style> * { margin: 0; padding: 0; } #left-bar { background-color: red; height: 100vh; width: 300px; } #content { background-color: blue; height: 100vh; flex-grow: 1; } body { display: flex; flex-direction: row; flex-wrap: nowrap; } </style> <div id="left-bar"> </div> <div id="content"> </div>
1.1 – 代码解析:
首先我们创建了两个Box: left-bar 和 content. 指定 left-bar 为红色, content 为蓝色
然后我们给 left-bar 的高度设定为 100vh (屏幕的100%高度) 并给 left-bar 指定了一个固定的宽度
对父容器body开启flex布局,将派来方式改为 row , 给content指定flex-grow为1, content就会默认填满剩余的所有空间
2- 两行布局
<!-- 两行布局 --> <style type="text/css"> * { margin: 0; padding: 0; } #line-top { background-color: aqua; width: 100vw; height: 100px; } #line-content { width: 100vw; background-color: aquamarine; flex-grow: 1; } #footer { height: 100px; background-color: beige; } body { /* 指定100vw和vh很重要,如果content容器的内容比较少,可能撑不开整个屏幕 */ width: 100vw; height: 100vh; display: flex; flex-direction: column; flex-wrap: nowrap; } </style> <div id="line-top"> </div> <div id="line-content"> <!-- <div style="height: 1000px;"></div> -->
flex详情:https://www.ruanyifeng.com/blog/2015/07/flex-grammar.html