前端如何保證 垂直 和 水平居中

在網頁製作的過程中,會遇到垂直居中水平劇中的問題,水平劇中比較方便,但是垂直劇中卻沒那麼方便。

(1)在這裡我主要用到方式是flex與box結合的方式,這種方式是css3新增屬性,不只是用於垂直劇中,更是可以替代float屬性的佈局,可用於分欄等等。IE89不支持就要用到box屬性。也建議大家多用這種技術。 阮一峰寫的介紹比較好,推薦大家閱讀,http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool 。

.div{

display: box; /* OLD - Android 4.4- */

display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */

display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */

display: -ms-flexbox; /* TWEENER - IE 10 */

display: -webkit-flex; /* NEW - Chrome */

display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */

/* 09版 */

-webkit-box-orient: vertical;

/* 12版 */

-webkit-flex-direction:column;

-moz-flex-direction: column;

-ms-flex-direction: column;

-o-flex-direction: column;

flex-direction: column;

/* 09版 */

-webkit-box-align: center;

/* 12版 */

-webkit-align-items: center;

-moz-align-items: center;

-ms-align-items: center;

-o-align-items: center;

justify-content:center;

align-items: center;

}

  1. position:absolute使絕對定位塊跳出了內容流,內容流中的其餘部分渲染時絕對定位部分不進行渲染。

  2. 由於內容塊被絕對定位,脫離了正常的內容流,瀏覽器會給margin-top,margin-bottom相同的值,使元素塊在先前定義的邊界內居中。

代碼如下

  1. div {

  2. margin: auto;

  3. position: absolute;

  4. top: 0; left: 0; bottom: 0; right: 0;

  5. }

當然可以通過設置top auto; left:10px;等來實現左側居中或者右側居中。

(3)其他的居中方式如單元格居中,

  1. .cell {

  2. display: table-cell;

  3. vertical-align: middle;

  4. }

  5. .block {

  6. width: 50%;

  7. margin: 0 auto;

  8. }

行內塊元素等,支持IE7。

在已知道寬度高度的情況下負外邊距方法也能很好的實現居於容器內。


分享到:


相關文章: