When designing a page, the layout of text is particularly important. As for the text centering method in CSS, it can be achieved in the following three ways.
1. text-align
Attribute
text-align
Attribute can be used to control the horizontal alignment of text, including left alignment and right alignment , centered, aligned at both ends, etc.
div{ text-align: center; }
where center
means centering. After using this attribute and setting the value to center
, the text will be automatically aligned in the center.
2. line-height
Attribute
line-height
The attribute represents the line height, which can be used to set the vertical centering of inline elements. When you set the line height equal to the box height, the text is centered vertically.
div{ height: 200px; line-height: 200px; text-align: center; }
This way you can center align the text.
3. display
and text-align
attributes
can convert text elements into flexible box layout through the display
attribute , and then control the horizontal centering through the justify-content
attribute. The justify-content
attribute can be set to different values, including center
, flex-start
, flex-end
, which respectively represent centering, Left-aligned, right-aligned, etc.
div{ display: flex; justify-content: center; }
The above are three methods for horizontally centering Chinese text in CSS, which can be used flexibly to make the page more beautiful. If you need to center the text vertically and horizontally, you can use a combination of the above two methods. At the same time, it is also necessary to note that the centering methods used by different element styles may be different, and the appropriate method must be selected according to the specific situation.
The above is the detailed content of How to center css text. For more information, please follow other related articles on the PHP Chinese website!