元素垂直水平居中的几种方法

已知宽高:

1、利用绝对定位盒模型的特性;

绝对定位的盒模型有以下特性:

left+right+width+水平方向的margin+padding=包含块的width;
top+bottom+height+垂直方向的margin+padding=包含块的height;

代码示例:

#parent{
      /* 父相子绝 */
      position: relative;
      /* 包含块的宽高必须是已知的 */
      width: 200px;
      height: 200px;
      border: 1px solid;
    }
    #child {
      /* 需要居中的元素绝对定位 */
      position: absolute;
      /* 居中的元素宽高要已知 */
      width: 50px;
      height: 50px;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      background-color: pink;
    }

2、利用margin为赋值进行反向偏移;

代码示例:

#parent{
      /* 父相子绝 */
      position: relative;
      /* 包含块的宽高必须是已知的 */
      width: 200px;
      height: 200px;
      border: 1px solid;
    }
    #child {
      /* 需要居中的元素绝对定位 */
      position: absolute;
      /* 居中的元素宽高要已知 */
      width: 50px;
      height: 50px;
      left: 50%;
      top: 50%;
      /* 元素向左和向上偏移自身宽高的一般 */
      margin-left: -25px;
      margin-top: -25px;
      background-color: pink;
    }

未知宽高

1、元素未设置宽高,宽高由内容撑开,利用transform来进行自身反向偏移;

代码示例:

#parent{
      /* 父相子绝 */
      position: relative;
      /* 包含块的宽高必须是已知的 */
      width: 200px;
      height: 200px;
      border: 1px solid;
    }
    #child {
      /* 需要居中的元素绝对定位 */
      position: absolute;
      /* 元素未设宽高,宽高由内容撑开 */
      left: 50%;
      top: 50%;
      /* 元素向左和向上偏移自身宽高的一般 */
      transform: translate3d(-50%,-50%,0);
      background-color: pink;
    }

2、利用flex来布局

代码示例:

#parent{
      /* 父相子绝 */
      position: relative;
      /* 包含块的宽高必须是已知的 */
      width: 200px;
      height: 300px;
      display: flex;
      /* 设置项目主轴方向为居中,默认主轴方向为水平 */
      justify-items: center;
      /* 设置项目辅轴方向为居中,默认辅轴方向为垂直方向 */
      align-items: center;
      border: 1px solid;
    }
    #child {
      /* 需要居中的元素绝对定位 */
      position: absolute;
      /* 元素未设宽高,宽高由内容撑开 */
      left: 50%;
      top: 50%;
      /* 元素向左和向上偏移自身宽高的一般 */
      transform: translate3d(-50%,-50%,0);
      background-color: pink;
    }
发布了133 篇原创文章 · 获赞 0 · 访问量 1698

猜你喜欢

转载自blog.csdn.net/weixin_43269800/article/details/104516089