css使用Flexbox实现水平垂直居中

时间:2017-11-03
CSS中一个相对比较新的特性,越来越多的应用使用它来开发。 甚至用它来解决传统的水平和垂直方向居中问题,本文章向大家介绍如何使用css3 Flexbox实现水平处置居中,需要的朋友可以参考一下。

伸缩盒模型(flexbox)是一个新的盒子模型,主要优化了UI布局。作为实际布局的第一个CSS模块(浮动真的应该主要用来制作文本围绕图片这样的效果),它使很多任务容易多。Flexbox的功能主要包手:简单使用一个元素居中(包括水平垂直居中),可以让扩大和收缩元素来填充容器的可利用空间,可以改变源码顺序独立布局,以及还有其他的一些功能。

下面我们来看一个简单的实例:(使用Flexbox实现水平垂直居中)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<style>
html, body {
    height: 100%;
}
body {
    margin: 0;
}
.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    align-items: center;
    justify-content: center;
}
.row {
    width: auto;
    border: 1px solid blue;
}
.flex-item {
    background-color: tomato;
    padding: 5px;
    width: 20px;
    height: 20px;
    margin: 10px;
    line-height: 20px;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}
</style>
</head>
<body>
  <div class="flex-container">
    <div class="container">
      <div class="row">
        <span class="flex-item">1</span>
      </div>
      <div class="row">
        <span class="flex-item">2</span>
      </div>
      <div class="row">
        <span class="flex-item">3</span>
      </div>
     <div class="row">
        <span class="flex-item">4</span>
    </div>
  </div>  
</div>
</body>
</html>

在线运行

缺省flexbox布局使用两个坐标来定位元素。 主要属性是flex-direction(只可以是row或者column),缺省值是row

为了让元素居中,我们使用如下方式:

  • 使用flex布局,即,display设置为flex
  • justify-content定义了flex元素将会根据主要坐标对齐(本例中是水平方向)
  • align-items将在本例中处理垂直方向