Home > Article > Web Front-end > How to center text in css
Methods for text centering: 1. Use the "text-align:center;" statement to set horizontal centering; 2. Use CSS3's flex layout to set vertical centering; 3. Use "vertical-align:middle;display: table-cell;" statement sets vertical centering.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
css sets the text to be horizontally centered
In CSS, you can use the text-align attribute to set the font to be horizontally centered. This property specifies the horizontal alignment of the text within the element, by using the center value to center the text.
text-align syntax:
text-align : left | right | center | justify
text-align parameter value and description:
left : left Alignment
right : Right alignment
center : Center
justify : Justify both ends ( Not recommended, usually not used by most browsers)
Our commonly used parameter values for text-align are left, right, center
The attributes are as follows Features:
1). The center of text-align is applied to a container. It only targets the text in the container and the container whose display is inline or inline-block. If the display of the container inside is inline or inline-block, block, the contents of the container inside will not be centered.
2), text-align is downwardly transitive and will continue to be passed to child elements. If you set a div, the content in its child divs will also be centered.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 水平居中</title> <style> .box { width: 400px; height: 100px; background: palegoldenrod; text-align:center; } </style> </head> <body> <div class="box">css文本文字--水平居中</div> </body> </html>
Rendering:
(Learning video sharing: css video tutorial)
css set text to be vertically centered
1. CSS3 flex layout to vertically center text
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: palegoldenrod; line-height:300px; /*设置为伸缩容器*/ 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:
##2. vertical-align:middle display:table-cell Center the text vertically
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box { width: 300px; height: 300px; background: palegoldenrod; vertical-align:middle; display:table-cell; } </style> </head> <body> <div class="box">css 文本文字--水平居中</div> </body> </html>Rendering:
Programming Video! !
The above is the detailed content of How to center text in css. For more information, please follow other related articles on the PHP Chinese website!