美文网首页
程序员花4小时总结:CSS如何去布局及运用方案

程序员花4小时总结:CSS如何去布局及运用方案

作者: 流浪的風 | 来源:发表于2017-09-05 11:40 被阅读0次

我们在日常开发中经常遇到布局问题,下面罗列几种常用的css布局方案

话不多说,上代码!

这里还是要推荐下我自己建的前端学习群:657137906,如果你正在学习前端,小编欢迎你加入,大家都是前端党,不定期分享干货(只有web前端相关的),包括我自己整理的一份2017最新的前端资料和零基础入门教程,欢迎初学和进阶中的小伙伴。

居中布局

以下居中布局均以不定宽为前提,定宽情况包含其中

1、水平居中


a) inline-block + text-align

tips:此方案兼容性较好,可兼容至IE8,对于IE567并不支持inline-block,需要使用css hack进行兼容

b) table + margin

tips:此方案兼容至IE8,可以使用代替css写法,兼容性良好

c) absolute + transform

tips:此方案兼容至IE9,因为transform兼容性限制,如果.child为定宽元素,可以使用以下写法,兼容性极佳

d) flex + justify-content

tips:flex是一个强大的css,生而为布局,它可以轻松的满足各种居中、对其、平分的布局要求,但由于现浏览器兼容性问题,此方案很少被使用,但是值得期待浏览器兼容性良好但那一天!

2、垂直

a) table-cell + vertial-align

.parent{display: table-cell;vertical-align: middle;}

tips:可替换成布局,兼容性良好

b) absolute + transform

tips:存在css3兼容问题,定宽兼容性良好

c) flex + align-items

.parent{display: flex;align-items: center;}

tips:高版本浏览器兼容,低版本不适用

3、水平垂直

a) inline-block + table-cell + text-align + vertical-align

tips:兼容至IE8

b) absolute + transform

tips:兼容性稍差,兼容IE10以上

c) flex

.parent{display: flex;justify-content: center;align-items: center;}

tips:兼容差

多列布局

1、一列定宽,一列自适应

a) float + margin

tips:此方案对于定宽布局比较好,不定宽布局推荐方法b

b) float + overflow

tips:个人常用写法,此方案不管是多列定宽或是不定宽,都可以完美实现,同时可以实现登高布局

c) table

d) flex

2、多列定宽,一列自适应

a) float + overflow

b) table

c) flex

3、一列不定宽,一列自适应

a) float + overflow

b) table

c) flex

4、多列不定宽,一列自适应

a) float + overflow

.left,.center{float: left;margin-right:20px;}.right{overflow: hidden;}.leftp,.centerp{width:100px;}

5、等分

a) float + margin

.parent{margin-left: -20px;}.column{float: left;width:25%;padding-left:20px;box-sizing: border-box;}

b) table + margin

.parent-fix{margin-left: -20px;}.parent{display: table;width:100%;table-layout: fixed;}.column{display: table-cell;padding-left:20px;}

c) flex

.parent{display: flex;}.column{flex:1;}.column+.column{margin-left:20px;}

6、等高

a) float + overflow

.parent{overflow: hidden;}.left,.right{padding-bottom:9999px;margin-bottom: -9999px;}.left{float: left;width:100px;}.right{overflow: hidden;}

b) table

.parent{display: table;width:100%;}.left{display:table-cell;width:100px;margin-right:20px;}.right{display:table-cell;}

c) flex

.parent{display:flex;width:100%;}.left{width:100px;}.right{flex:1;}

并排等分,单排对齐靠左布局

效果图

flex

.main{display: flex;flex-flow: row wrap;justify-content: space-between;}.item{display: inline-block;}.empty{height:0;visibility: hidden;}

最后在说几句:

厉害程序员相对于普通程序员的优势在于:

写出的代码更容易排错,不是高手的代码就不会错,而是高手的代码出了错容易找。高手的代码可读性一定很好,模块清晰,命名规范,格式工整,关键的地方有注释,出了异常有log,自然容易排错,即使交给别人去debug也是比较容易的。

相关文章

网友评论

      本文标题:程序员花4小时总结:CSS如何去布局及运用方案

      本文链接:https://www.haomeiwen.com/subject/mmmacxtx.html