Several methods to achieve horizontal centering and vertical centering in CSS

Method 1: Horizontally and vertically center text and line elements

{
    text-align: center; // 水平居中
    line-height: 盒子高度; // 垂直居中,只适合行元素
}

Advantages: simple and practical;

Disadvantages: only suitable for single lines of text and line element content;

Method 2: Center the box based on the known width and height of the box;

{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 100px;
    margin-top: -50px; // 盒子的一半高度
    margin-left: -100px; // 盒子的一半宽度
}

// 以上代码可优化为下方代码:
{
    position: absolute;
    width: 200px;
    height: 100px;
    top: calc(50% - 50px);
    left: calc(50% - 100px);
}

Advantages: Both row elements and block elements can be centered;

Disadvantages: Need to fix the width and height of the box;

Method 3: Use absolute positioning + CSS transformation to center the box

{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Advantages: Both row elements and block elements can be centered, and there is no need to fix the width and height of the box;

Disadvantage: When the height of the box exceeds the height of the screen, the top of the box will be cropped by the viewport; [Viewport: represents the width and height of the screen seen visually]

Method 4: Use flex layout to center the box

// 父盒子
{
    display: flex;
}
// 子盒子
{
    margin: auto;
}

Advantages: Simple implementation, no need to set the size of the parent box or child box;

Disadvantages: Some lower version browsers may not support it;

Method 5: Use vertical-align + line-height attributes to center vertically

.div {
    width: 364px;
    height: 221px;
    line-height: 221px;
    text-align: center;
    img {
      vertical-align: middle;
      width: 48px;
      height: 48px;
    }
  }

Advantages: Simple and convenient to implement, similar to method 1;

Disadvantage: Need to know the height of the parent container, suitable for vertical centering of images in divs;

The above content is the centering method I summarized during development. Any similarity is purely coincidental! In addition, if there are any errors, please point them out!

Guess you like

Origin blog.csdn.net/listener_life/article/details/129812584