如何用CSS实现中间自适应,两边定宽三栏布局
1.前言
用css实现“两边定宽,中间自适应的三栏布局”这个问题应该是在前端面试中被面试官提问到的高频问题了,一般当面试者写出一种实现方法之后,面试官还会问你还有没有别的方法,尽量多的写出几种实现方法。
2.实现原理
要想实现这种“两边定宽,中间自适应的三栏布局”其实也不难,无外乎把握住以下几点:
- 要想中间自适应,那么中间的div不能设置宽度width,这样宽度就会随着浏览器窗口自适应。
- 由于div是块级元素,要想三个div处于同一行,那么两边的div就要脱离文档流。
- CSS3的flex伸缩布局。
- 表格table布局。
- 网格布局。
3.具体实现
下面就按照上面所说的实现原理,列举以下几种实现方式:
3.1 浮动解决方案
<style> .layout-float .right{ float: right; width: 300px; height: 100px; background-color: red; } .layout-float .left{ float: left; width: 300px; height: 100px; background-color: blue; } .layout-float .center{ height: 100px; background-color: yellow; } </style> <div class="right"></div> <div class="left"></div> <div class="center"><h1>浮动解决方案</h1></div>
3.2 绝对定位解决方案
<style> .layout-absolute .right{ width: 300px; height: 100px; right: 0px; position: absolute; background-color: red; } .layout-absolute .left{ width: 300px; height: 100px; left: 0px; position: absolute; background-color: blue; } .layout-absolute .center{ left: 300px; right: 300px; height: 100px; position: absolute; background-color: yellow; } </style> <div class="left"></div> <div class="center"><h1>绝对定位解决方案</h1></div> <div class="right"></div>
3.3 Flex伸缩布局解决方案
<style> .layout-flex .left-center-right{ display: flex; } .layout-flex .left-center-right .left{ width: 300px; height: 100px; background-color: blue; } .layout-flex .left-center-right .center{ flex: 1; background-color: yellow; } .layout-flex .left-center-right .right{ width: 300px; height: 100px; background-color: red; } </style> <div class="left-center-right"> <div class="left"></div> <div class="center"><h1>Flex伸缩布局解决方案</h1></div> <div class="right"></div> </div>
3.4 表格布局解决方案
<style> .layout-table .left-center-right{ width: 100%; display: table; height: 100px; } .layout-table .left-center-right>div{ display: table-cell; } .layout-table .right{ width: 300px; height: 100px; background-color: red; } .layout-table .left{ width: 300px; height: 100px; background-color: blue; } .layout-table .center{ height: 100px; background-color: yellow; } </style> <div class="left-center-right"> <div class="left"></div> <div class="center"><h1>表格布局解决方案</h1></div> <div class="right"></div> </div>
3.5 网格布局解决方案
<style> .layout-grid .left-center-right{ width: 100%; display: grid; grid-template-rows: 100px; grid-template-columns: 300px auto 300px; } .layout-grid .right{ background-color: red; } .layout-grid .left{ background-color: blue; } .layout-grid .center{ background-color: yellow; } </style> <div class="left-center-right"> <div class="left"></div> <div class="center"><h1>网格布局解决方案</h1></div> <div class="right"></div> </div>
4. 效果图
(完)
免责声明
- 本博客所有文章仅用于学习、研究和交流目的,欢迎非商业性质转载。
- 博主在此发文(包括但不限于汉字、拼音、拉丁字母)均为随意敲击键盘所出,用于检验本人电脑键盘录入、屏幕显示的机械、光电性能,并不代表本人局部或全部同意、支持或者反对观点。如需要详查请直接与键盘生产厂商法人代表联系。挖井挑水无水表,不会网购无快递。
- 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高(其实是个菜B),不足和错误之处在所难免,希望大家能够批评指出。
- 博主是利用读书、参考、引用、抄袭、复制和粘贴等多种方式打造成自己的文章,请原谅博主成为一个无耻的文档搬运工!
posted on 2018-08-12 13:55 难凉热血,码梦为生! 阅读(644) 评论(0) 编辑 收藏 举报