This article mainly introduces in detail the various methods of vertical centering of p in the CSS tutorial, including the method of vertically centering multi-line text. Interested friends can refer to it
is talking about When it comes to this question, someone may ask if there is no vertical-align attribute in CSS to set vertical centering? Even if some browsers don't support it, I only need to do a little CSS Hack technology! So I have to say a few words here. There is indeed a vertical-align attribute in CSS, but it only takes effect for elements with valign attributes in (X)HTML elements, such as < in table elements. ;td>,
, do not have valign attributes, so using vertical-align will not work on them.
1. Single-line vertical centering
If there is only one line of text in a container, it is relatively simple to center it. We only need to set its actual height height can be equal to the heightline-height of the row.
For example:
p { height:25px; line-height:25px; overflow:hidden; }
This code is very simple. The overflow:hidden setting is used later to prevent the content from exceeding the container or automatically wrapping lines, so that the vertical centering effect cannot be achieved.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> 单行文字实现垂直居中 </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-size:12px;font-family:tahoma;} p { height:25px; line-height:25px; border:1px solid #FF0099; background-color:#FFCCFF; } </style> </head> <body> <p>现在我们要使这段文字垂直居中显示!</p> </body> </html>
2. Vertical centering of multi-line text of unknown height
If a piece of content, its height is adjustable Then we can use the last method used to achieve horizontal centering mentioned in the previous section, which is to set Padding so that the upper and lower padding values are the same. Again, this is a way of "looking" vertical centering, it's just a way of making the text completely fill the
. You can use code similar to the following:
p { padding:25px; }
The advantage of this method is that it can run on any browser, and the code is very simple, but the prerequisite for this method is that the height of the container must be scalable of.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> 多行文字实现垂直居中 </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-size:12px;font-family:tahoma;} p { padding:25px; border:1px solid #FF0099; background-color:#FFCCFF; width:760px; } </style> </head> <body> <p><pre class="brush:php;toolbar:false">现在我们要使这段文字垂直居中显示! p { padding:25px; border:1px solid #FF0099; background-color:#FFCCFF; }