Home > Article > Web Front-end > N ways to set vertical centering of DIV in CSS, compatible with IE browser
When talking about this issue, some people may ask, isn’t there a 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 on elements with valign attributes in (X)HTML elements, such as b6c5a531a458a2e790c1fd6421739d1c, 6a4b373248ac4e3377b5731bd5668ee5, 63bd76834ec05ac1f4c0ebbeaafb0994, etc. Elements like dc6dce4a544fdca2df29d5ac0ea9906b, 45a2772a6b6107b401db3c9b82c049c2 do not have valign attributes, so using vertical-align will not work on them.
Tips: The perfect solution is at the end of the article!
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 to be equal to the height of the line-height.
如: 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 causing automatic line wrapping, 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>
If the height of a piece of content is variable, then we can use the last method mentioned in the previous section to achieve horizontal centering, which is to set the 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 dc6dce4a544fdca2df29d5ac0ea9906b. You can use code similar to the following:
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.
<!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">现在我们要使这段文字垂直居中显示!