Home > Article > Web Front-end > CSS element vertically centered
The troublesome problem with CSS is vertical centering. There are several ways to achieve vertical centering, but each method has certain limitations, so vertical centering can be used according to actual business scenarios.
1. The content in the container is only one line of text
<!DOCTYPE html> <html> <style> * { padding: 0; margin: 0; } div { height: 60px; background-color: #1888fa; color: white; } span { line-height: 60px;/* 设置一个大的行高,让它等于理想的容器高度。 这样会让容器高度扩展到能够容纳行高。如果内容不是行内元素,可以设置为inline-block。 */ } </style> <body> <div> <span>测试</span> </div> </body> </html>
2. The container is natural Height
The simplest vertical centering method in CSS is to give the container equal top and bottom padding, allowing the container and content to determine their own height. See the example below, which vertically centers the content in the parent container by setting padding-top
and padding-bottom
to equal values.
<!DOCTYPE html> <html> <style> * { padding: 0; margin: 0; } div { padding-top: 20px; padding-bottom: 20px; background-color: #1888FA; color: white; } </style> <body> <div> <span>测试</span> </div> </body> </html>
3. Use FlexBox
<!DOCTYPE html> <html> <style> * { padding: 0; margin: 0; } div { height: 60px; display: flex; align-items: center; justify-content: center; background-color: #1888fa; color: white; } </style> <body> <div> <span>测试</span> </div> </body> </html>
Recommended: "2021 CSS Interview Questions Summary (Latest)》
The above is the detailed content of CSS element vertically centered. For more information, please follow other related articles on the PHP Chinese website!