CSS——水平垂直居中

83 阅读1分钟

垂直居中

  • 文本: line-height=height
  • 元素:
    • 方法一:【父相子绝】
      • 父元素: position:relative 子元素: position:absolute; top:50%; margin-top:1/2子元素height (margin-top也可以用transform代替);
    • 方法二:【flex布局】父元素flex布局 display: flex; 子元素 margin: auto 0;
  • 子元素布满父元素且文本垂直居中: 【table布局】父元素display: table;子元素display:table-cell;vertical-align:middle;

水平居中

  • 行内元素: text-align:center /或将为块元素的子元素转为行内块元素:display:inline-block再使用此方法;
  • 块元素:
    • 子元素宽度已知:
      • 方法一:【父相子绝】
        • 父元素: position:relative 子元素: position:absolute; left:50%; margin-left:1/2子元素width;
      • 方法二:【子元素 margin: 0 auto;】
    • 子元素宽度未知
      • 方法一:【table布局】子元素 display: table; margin: auto;
      • 方法二:【子绝+位移】子元素 position: absolute; transform:translateX(50%)
      • 方法三:【flex布局】父元素 display: flex;justify-content: center;
      • 方法四:【flex布局】父元素 display: flex; 子元素 margin:0 auto;

延申: auto的作用:程序会自动计算剩余部分的空白长度,把其等分再作为子元素外边距