Interview subjects required
Horizontal center
Inline elements
inline/inline-block/inline-table/inline/flex:
text-aligin:center
Copy the code
Block-level elements
Fixed width:
margin-left: auto;
margin-right: auto;
Copy the code
Multiple horizontal block-level elements
One of two ways
- The display property is set to inline-block
display: inline-block; text-align:center; Copy the code
- Flex layout
display: flex; justify-content:center Copy the code
Multiple vertical block-level elements
margin-left: auto;
margin-right: auto;
Copy the code
Vertical center
Inline elements
- Padding-top and padding-bottom are given the same size
- Line-height is equal to height without newline
Block-level elements
- Fixed height: Margin-top is half the height of the container by setting top50%
- Height is not fixed: by setting top50% then
transform: translateY(-50%);
- Flex layout
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
Copy the code
Horizontal + vertical center
Wide high fixed
Top left 50% and margin-top margin-left are half the height and width of the container, respectively
The width and height are not fixed
Top left 50% and Transform: Translate (-50%, -50%)
flex
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Copy the code