This article is a correction and addition to the “CSS Refueling Pack vertical Center” three months ago, because there is no example in this article, so keep the old article, address ⬇️

Juejin. Cn/post / 689074…

Why is vertical center hard to do?

Has to do with the backtracking mechanism of CSS; Since CSS is not orthogonal, tuning a single property may change other properties as well.

1. You don’t know your own height and the height of the parent element

parentElement{ position: relative; } childElement{ position: absolute; top: 50%; Transform: translateY(-50%) /*Copy the code

2. If the parent container has only one element, and the height is set, you can use relative positioning for the child elements

parentElement{
    height: xxx;
}
childElement {
    position: relative;
    top: 50%;
    transform: translateY(-50%)
}
Copy the code

Margin: auto; margin: auto; margin: auto; margin: auto;

parentElement{
    position: relative;
    width: xxx;
    height: xxx;
}
childElement{
    position: absolute;
    width: xxx;
    height: xxx;
    top: 0;
    bottom: 0;
    margin: auto;
}
Copy the code

4. Regardless of compatibility with older browsers, the parent container can use Flex layout

parentElement{ display: flex; display: -webkit-flex; /* Safari compatible */ align-items: center; /* Specify vertical center */}Copy the code

5. Flex -direction: column;

parentElement{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: xxx;
    height: xxx;
}
childElement{
    width: xxx;
    height: xxx;
}
Copy the code

6. Display: table;

parentElement{
    display: table;
}
childElement{
    display: table-cell;
    vertical-align: middle;
}
Copy the code

7. Display: grid; Set two more helper elements

parentElement{
    display: grid;
    width: xxx;
    height: xxx;
}
.targetChild{
    background: xxx;
}
.aboveTarget, .belowTarget {
    background: yyy;
}
Copy the code