Centered horizontally, vertically centered

First, the middle level

(1) the line element to its parent element to text-align: center can;

(2) a bulk element, which is provided margin: 0 auto can;

(3) if the sub-element comprising float: left attribute; child element to make the middle level, the need to set the width of the parent element fit-content, and with the margin: 0 auto, as follows:

  .parent{

    width: -moz-fit-content;

    width: -webkit-fit-content;

    width:fit-content;

    margin:0 auto;

  }

  PS: Fit-Content currently only supports Chrome and firefox

(4)flex(2012)

  .son{

    display:flex;

    justify-content: center;

  }

(5) flex (2009), the parent element display: box; box-pack: center; following settings:

 

  .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) use of the new CSS3 transform property, provided the following sub-elements: 

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

(7) using absolute positioning mode, and a negative margin-left, subelement (fixed width) as follows:

  .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)

 

Guess you like

Origin www.cnblogs.com/chen-fei666/p/10966663.html