水平居中,垂直居中

一、水平居中

(1)行内元素,给其父元素添加text-align:center即可;

(2)块状元素,该元素设置margin:0 auto即可;

(3)若子元素包含float:left属性;为让子元素水平居中,需给父元素宽度设置fit-content,并配合margin:0 auto,设置如下:

  .parent{

    width: -moz-fit-content;

    width: -webkit-fit-content;

    width:fit-content;

    margin:0 auto;

  }

  ps:fit-content目前只有Chrome和firefox支持

(4)flex(2012)

  .son{

    display:flex;

    justify-content: center;

  }

(5)flex(2009),父元素display: box;box-pack: center;如下设置:

  .parent {
    display: -webkit-box;
    -webkit-box-orient: horizontal;
    -webkit-box-pack: center;
    display: -moz-box;
    -moz-box-orient: horizontal;
    -moz-box-pack: center;
    display: -o-box;
    -o-box-orient: horizontal;
    -o-box-pack: center;
    display: -ms-box;
    -ms-box-orient: horizontal;
    -ms-box-pack: center;
    display: box;
    box-orient: horizontal;
    box-pack: center;
  }

(6)使用CSS3中新增的transform属性, 子元素设置如下: 

  .son{
    position:absolute;
    left:50%;
    transform:translate(-50%,0);
  }

(7)使用绝对定位方式, 以及负值的margin-left, 子元素(宽度固定)设置如下:

  .son{

    position:absolute;

    width:固定;

    left:50%;

    margin-left:-0.5宽度

  }

(8)使用绝对定位方式, 以及left:0;right:0;margin:0 auto; 子元素(宽度固定)设置如下:

  .son{

    position:absolute;

    width:固定;

    left:0;

    right:0;

     margin:0 auto

  }

二、垂直居中

(1)若元素是单行文本,则可设置line-height即可;

(2)若元素是行内块级元素,用display:inline-block;vertical-align:middl和一个伪元素让内容块垂直居中:

  .parent:after,.son{

    display:inline-block;

    vertical-align:middle;

  }

  .parent:after{

    content:'';

    height:100%;

  }

(3)元素高度不固定,可使用vertical-align:middle,但是只用父元素是th或者td时此方法才有效,所以为了使用vertical-align,需要设置父元素display:table,子元素display:table-cell;vertical-  align:middle;

  优点:元素高度可以动态改变,不需在css中定义,如果父元素没有足够空间,该元素内容也不会被截断

  缺点:ie6~7甚至ie8beta中无效

(4)flex(2012)

  .parent{

    display:flex;

    align-items:center

  }

  优点:1、元素块的宽高任意  2、可用于更复杂高级的布局技术中

  缺点:1、ie9-不适应  2、需要浏览器前缀  3、渲染有一些问题

(5)flex(2009)

猜你喜欢

转载自www.cnblogs.com/chen-fei666/p/10966663.html