水平居中 和 垂直居中 方法总结

水平居中

  行内元素:

     * 如果父元素是块级元素,则直接给父元素设置text-align:center;

     * 如果父元素是不是块级元素,先将父元素设置为块级元素,再给父元素设置text-align:center;

  块级元素:

    * 需要谁居中,给其设置 margin: 0 auto

    * 父元素设置相对定位,子元素设为: position:absolute;left: 50%;margin-left:-元素宽度的一半

    *父元素设置相对定位,子元素设为: position:absolute;left: 50%;transform:translateX(-50%)

    * 使用flexbox布局,父元素设置: dispaly: flex;justify-content: center;

垂直居中

  行元素:

     单行的行内元素:设置行高等于高度即可 ling-height= height

    *  多行的行内元素: 给父元素设置 display: table-cell;vertical-align: middle

  块级元素:

    *父元素设置相对定位,子元素设置:position:sabsolute;top: 50%;margin-top:-元素高度的一半

     * 父元素设置相对定位,子元素设置: position:absolute;top: 50%; transform:translateY(-50%);

    * 使用flexbox布局,父元素设置:display: flex;align-items: center;

水平垂直居中

  已知宽高:

    * 设置父元素为相对定位,子元素设置:position:absolute;top:0;left:0;right:0;bottom:0;width: 200px;height:200px;margin:auto;

    * 设置父元素为相对定位,子元素设置:position:absolute;left: 50%;top:50%;width:200px;height:200px;margin-top:-100px;margin-left: -100px;

  未知宽高:

    *设置父元素为相对定位,子元素设置:position:absolute;top: 50%;left:50%;transform:translate(-50%,-50%);

    * 使用flexbox布局:父元素设置:display:flex;align-items:center;justify-content:center;

    * 使用flexbox布局:父元素设置:display:flex; 子元素设置 margin:auto

      注意:弹性盒子只要给弹性子元素设置 margin:auto,就可以使弹性子元素上下左右居中

 

<div class="parent">
    <h1 class="child">快速居中对齐</h1>
</div>
.parent{
      width: 500px;
      height: 200px;
      background-color: blue;
      display: flex;
  }
.child{
  margin:auto
}

 

  

 

posted @ 2019-08-13 17:05  yangkangkang  阅读(227)  评论(0编辑  收藏  举报