一面二面(1)之CSS实现三栏布局(5种)

    技术2023-05-20  72

    常见的布局方式: float布局、Position定位、table布局、弹性(flex)布局、网格(grid)布局 1、float布局:脱离文档流,但是不脱离文本流。

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>浮动实现三栏布局</title> <style type="text/css"> *{ margin: 0; padding: 0; } .left{ float: left; width: 300px; height: 100px; background: #631D9F; } .right{ float: right; width: 300px; height: 100px; background: red; } .center{ margin-left: 300px; margin-right: 300px; background-color: #4990E2; } </style> </head> <body> <article class="main"> <div class="left"></div> <div class="right"></div> <div class="center"><h2>浮动布局</h2> </div> </article> </body> </html>

    2、Position布局:我们要给其父元素添加 position:relative属性, 这样这三个子元素可以相对于父元素进行绝对定位。

    .left{ position: absolute; left: 0; width: 300px; background-color: red; } .center{ position: absolute; left: 300px; right: 300px; background-color: blue; } .right{ position: absolute; right: 0; width: 300px; background-color: #3A2CAC; }

    3、table布局:

    .main{ width: 100%; display: table; } .left,.center,.right{ display: table-cell; } .left{ width: 300px; background-color: red; } .center{ background-color: blue; } .right{ width: 300px; background-color: red; }

    4、弹性(flex)布局:

    .main { display: flex; } .left{ width: 400px; background-color: red; } .center{ background-color: blue; flex-grow:1 } .right{ background-color: red; width: 400px; }

    5、网格(gird)布局:gird-template-columns设置列的宽度,grid-template-rows设置列的高度

    .left{ background-color: red; } .center{ background-color: blue; } .right{ background-color: red; } .main{ width: 100%; display: grid; grid-template-rows: 100px; grid-template-columns: 300px auto 300px; }

    总结: 以上提供了5种实现三栏布局的方式那么他们的优缺点呢?

    1、float布局是现在用的比较多的布局很多门户网站目前使用这个布局方式,使用的时候只需要注意一定要清除浮动。

    2、Position布局只是根据定位属性去直接设置元素位置,个人感觉不太适合用做页面布局

    3、table布局使用起来方便,兼容性也不存在问题,不利于搜索引擎抓取信息

    4、flex布局比较强大,但是还是存在IE上兼容性问题,只能支持到IE9以上

    5、grid布局很强大,但是兼容性很差。

    Processed: 0.015, SQL: 9