css簡單布局及居中方法

css簡單布局及居中方法

1. 左右布局

html:

<div class="clearfix wrapper"> <div class="left"> left </div> <div class="right"> right </div></div>

css:

.clearfix::after{ content: ; display: block; clear: both;}.left{ float: left;}.right{ float: right;}.wrapper{ height: 100px; padding: 10px; text-align: center; background: rgba(0,0,0,.4); color: #fff;}.wrapper>div{ width: 50%; height: 100%; line-height: 100px;}.wrapper>div.left{ background: blue;}.wrapper>div.right{ background: red;}

效果:

JS Bin?

js.jirengu.com圖標

2. 左中右布局(類似左右布局)

JS Bin?

js.jirengu.com圖標

3. 水平居中

  • 行內元素:

<!--1--> <div class="wrapper inline-wrapper"> <span>行內元素水平居中</span> </div>塊級元素:

html:

<!--2.a--> <div class="wrapper block-wrapper-a"> <div>塊級元素水平居中a</div> </div> <!--2.b--> <div class="wrapper block-wrapper-b"> <div>塊級元素水平居中b</div> </div> <!--2.c--> <div class="wrapper block-wrapper-c"> <div>塊級元素水平居中c</div> </div> <!--2.d--> <div class="wrapper block-wrapper-d"> <div>塊級元素水平居中d</div> </div>

css:

.wrapper{ padding: 5px; height: 22px; margin-bottom: 10px; background: rgba(0,0,0,0.4); text-align: center; color: #fff;}.wrapper div{ width: 50%; background: yellow; color: #000;}/* 1 */.inline-wrapper{ text-align: center;}/* 2.a */.block-wrapper-a div{ margin: 0 auto;}/* 2.b */.block-wrapper-b div{ position: absolute; left: 50%; margin-left: -120px;}/* 2.c */.block-wrapper-c div{ position: absolute; left: 50%; transform: translateX(-50%);}/* 2.d */.block-wrapper-d{ display: flex; flex-direction: row; justify-content: center;}

JS Bin?

js.jirengu.com圖標

方法3用到css3的偏移屬性,方法4用到flex布局方法,都可能會有瀏覽器兼容問題,需要注意。具體可參考:

Can I use... Support tables for HTML5, CSS3, etc?

caniuse.com

Can I use... Support tables for HTML5, CSS3, etc?

caniuse.com

4. 垂直居中

垂直居中相對水平居中來講,基本上就是將left改為top, margin-left改為margin-top, translateX改為translateY, justify-content: center改為align-items: middle;即可。

5. 等其他小技巧

之前寫過一篇利用css3的display: inline-block;來實現左右滑動的文章,可以參考:

css display: inline-block;實現橫向滾動?

zhuanlan.zhihu.com圖標

還有個只用一個div來實現陰陽??圖的小demo(充分利用border, ::after, ::before偽元素),可以參考:

太極?

legend1992.github.io


推薦閱讀:

js對象
webpack學習筆記- 深入學習
webpack原理與實戰
前端教程,web前端教程全集,學完你就是大神!
響應式布局

TAG:HTML | CSS | 前端開發 |