Home > Article > Web Front-end > css code to realize text vertical centering_Experience exchange-www.jb51.net-css vertical centeringwww.jb51.net css vertical centering
How to set the text in CSS so that the text in the object is vertically centered on the object is also a problem that bothers many friends. Many codes on the Internet today are not browser compatible. I sorted out the relevant methods on the Internet and made some changes. It is completely compatible with all mainstream browsers.
Let’s talk about vertical centering methods in different situations.
1. A line of text is vertically centered
Look at the following code:
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
一行文字垂直居中,此对象高度为20px
Method: line-height:20px. Set the same row height and object height.
Description: This setting is simple and compatible with various browsers, and supports inline objects. But if it is an object with a fixed height, only one line can be displayed. When there are two lines of text, if "overflow:hidden" is not set, the object will be stretched.
2. Multi-line text and highly adaptive
Please see the following code:
Method: padding-top:10px; padding-bottom: 10px. Set the same top and bottom padding.
Description: Compatible with various browsers, supports inline objects, and also supports non-text objects, such as img. But one disadvantage is that the height of the object cannot be fixed.
3. Vertically center multi-line text with a fixed height
This method is more complicated, and I will explain it in detail. Let’s look at the code first:
Method:
(1) vertical-align:middle; display:table-cell. The meaning of this method is to force the object to a Table. The function of vertical-align:middle is the same as valign="center" in the table.
This is originally a very convenient attribute, but IE does not support this attribute. In order to make each browser compatible, we have to think of other methods.
(2) Create a sub-object within the object, and create a sub-object or paragraph within the sub-object. In the web page:
There are multi-line text here, the height is 50px There are multi-line text here, the height is 50px
phpcnltphpc n/p>