Home > Article > Web Front-end > How to set vertical centering in css
How to set vertical centering in css: 1. Use the line-height attribute to center the text vertically; 2. Use CSS3 flex layout to center the text vertically; 3. Use absolute positioning and transform to center the block elements vertically; 4. Use flex layout to vertically center block elements.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
css sets the text to be vertically centered
1. Line-height makes the text vertically centered
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: paleturquoise; line-height:300px; } </style> </head> <body> <div class="box">css 垂直居中了--文本文字</div> </body> </html>
Rendering:
This will allow the text in the div to be centered horizontally and vertically
2. CSS3 flex layout Center the text vertically
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 200px; background: paleturquoise; /*设置为伸缩容器*/ display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; /*垂直居中*/ -webkit-box-align: center;/*旧版本*/ -moz-box-align: center;/*旧版本*/ -ms-flex-align: center;/*混合版本*/ -webkit-align-items: center;/*新版本*/ align-items: center;/*新版本*/ } </style> </head> <body> <div class="box">css 垂直居中--文本文字(弹性布局)</div> </body> </html>
Rendering:
css sets block elements to be vertically centered
1. Use absolute positioning and transform (unknown element height)
If we don’t know the height of the element, then we need to position the element first The center position of the container, and then use the translate attribute of transform to coincide the center of the element with the center of the parent container to achieve vertical centering:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; position: relative; } .child{ background: #93BC49; position: absolute; top: 50%; transform: translate(0, -50%); } </style> </head> <body> <div class="box"> <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div> </div> </body> </html>
Rendering:
2. Use flex layout
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; display: flex; flex-direction: column; justify-content: center; } .child{ width: 300px; height: 100px; background: #08BC67; line-height: 100px; } </style> </head> <body> <div class="box"> <div class="child">css 垂直居中了--弹性布局</div> </div> </body> </html>
Rendering:
(Learning video sharing: css video tutorial )
The above is the detailed content of How to set vertical centering in css. For more information, please follow other related articles on the PHP Chinese website!