布局效果
方法一:flex布局
父元素设置display: flex;
子元素.left, .right都设置宽高为200px,.middle设置flex:1;
贴上代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container { display: flex; width: 100%; height: 100%; } .left, .right { width: 200px; height: 200px; } .left { background: #ccc; } .right { background: pink; } .middle { flex: 1; height: 200px; background: #abcdef; } </style> </head> <body> <div class="container"> <div class="left"></div> <div class="middle"></div> <div class="right"></div> </div> </body> <script> </script> </html>
方法二:float + margin
元素.left, .right都设置宽高为200px, .left左浮动, .right右浮动。
.middle设置margin: 0 200px;
贴上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container { width: 100%; height: 100%; } .left, .right { width: 200px; height: 200px; } .left { background: #ccc; float: left; } .right { background: pink; float: right; } .middle { height: 200px; background: #abcdef; margin: 0 200px; } </style> </head> <body> <div class="container"> <div class="left"></div> <div class="right"></div> <div class="middle"></div> </div> </body> <script> </script> </html>
注意:middle要放在最后,因为float元素会为块级元素让出位置。如果middle在right前,则right会置于下一行(为块级元素middle让出一行位置)
方法三:position + margin
父元素设置position: relative, 子元素.left, .right都设置position: absolute, 200px, height: 200px;
.left设置left: 0, top: 0; .right设置right: 0, top: 0;
.middle设置margin: 0 200px;
贴上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container { width: 100%; height: 100%; position: relative; } .left, .right { width: 200px; height: 200px; position: absolute; top: 0; } .left { background: #ccc; left: 0; } .right { background: pink; right: 0; } .middle { height: 200px; background: #abcdef; margin: 0 200px; } </style> </head> <body> <div class="container"> <div class="left"></div> <div class="right"></div> <div class="middle"></div> </div> </body> <script> </script> </html>