css:flex和float margin布局
一、flex布局
顶部,底部固定,中间自适应(中间左固定,右自适应)。
<body> <div class="container"> <div class="header"></div> <div class="content"> <div class="left"></div> <div class="right"></div> </div> <div class="footer"></div> </div> </body> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; } .container { height: 100%; background-color: yellow; display: flex; flex-direction: column; } .header { height: 80px; background-color: red; } .content { flex: 1; display: flex; background-color: green; } .left { width: 200px; background-color: hotpink; } .right { flex: 1; background-color: yellow; } .footer { height: 80px; background-color: blue; } </style>
三栏平均分布局(两边可以定框)
<body> <div class="container"> <div class="left"></div> <div class="middle"></div> <div class="right"></div> </div> </body> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; } .container { height: 100%; background-color: yellow; display: flex; } .left { flex: 1; background-color: red; } .middle { flex: 1; background-color: green; } .right { flex: 1; background-color: blue; } </style>
二、float + margin
两栏布局
宽高实际需要,不设置高度,通过子元素自动撑起。
<body> <div class="container"> <div class="left"></div> <div class="right"></div> </div> </body> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; } .container { height: 100%; background-color: yellow; } .left { float: left; width: 200px; height: 100%; background-color: red; } .right { margin-left: 200px; height: 100%; background-color: green; } .container::after{ content: ‘‘; display: block; clear: both; } </style>
/* 不需要清除浮动也可以 */
两边固定中间自适应
<body> <div class="container"> <div class="left"></div> <div class="right"></div> <div class="middle"></div> </div> </body> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; } .container { height: 100%; background-color: yellow; } .left { float: left; width: 200px; height: 100%; background-color: red; } .right { float: right; width: 200px; height: 100%; background-color: green; } .middle { margin-left: 200px; margin-right: 200px; height: 100%; background-color: blue; } </style>
因为排在后面的浮动元素会把前面的块级元素的位置空出来,所以这里右边的浮动元素把上面的位置空了下来,所以元素排序为:
<body> <div class="container"> <div class="left"></div> <div class="right"></div> <div class="middle"></div> </div> </body>