How to set the vertical centering of a div in css: 1. Set its actual height height to be equal to the height of the row [line-height]; 2. Set the padding so that the upper and lower padding values are the same.
The operating environment of this tutorial: windows7 system, css3 version, DELL G3 computer.
How to set div vertical centering in css:
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 to be equal to the height line-height of the row.
For example:
div { 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;} div { height:25px; line-height:25px; border:1px solid #FF0099; background-color:#FFCCFF; } </style> </head> <body> <div>现在我们要使这段文字垂直居中显示!</div> </body> </html>
2. Vertical centering of multiple lines of text of unknown height
If the height of a piece of content is variable, then we can use the method mentioned in the previous section The last method used to achieve horizontal centering is to set the padding so that the padding values for the upper and lower sides are the same. Again, this is a way of "looking" vertical centering, it's just a way of making the text completely fill the
div { 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 the application of 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;} div { padding:25px; border:1px solid #FF0099; background-color:#FFCCFF; width:760px; } </style> </head> <body> <div><br> <pre class="brush:php;toolbar:false">现在我们要使这段文字垂直居中显示!