Table of Contents
1. Single line vertically centered " >1. Single line vertically centered
2. Vertical centering of multiple lines of unknown height text" >2. Vertical centering of multiple lines of unknown height text
3. Centering multi-line text with fixed height" >3. Centering multi-line text with fixed height
4. Solution in Internet Explorer" >4. Solution in Internet Explorer
五、完美的解决方案" >五、完美的解决方案
六、实测可以完美实现各种浏览器兼容的居中方案 " >六、实测可以完美实现各种浏览器兼容的居中方案 
Home Web Front-end HTML Tutorial N ways to set vertical centering of DIV in CSS, compatible with IE browser

N ways to set vertical centering of DIV in CSS, compatible with IE browser

Jul 06, 2016 pm 01:28 PM

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 , < in table elements. th>, , etc. Elements like

, 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!

1. Single line vertically centered

 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;   
}
Copy after login

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>
Copy after login

2. Vertical centering of multiple lines of unknown height text

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

. You can use code similar to the following:

div {   
padding:25px;   
} 
Copy after login

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">现在我们要使这段文字垂直居中显示!
    

  
Copy after login

3. Centering multi-line text with fixed height

At the beginning of this article, we have said that the vertical-align attribute in CSS will only work on (X)HTML tags with valign attributes, but there is also a display attribute in CSS that can simulate

, so we can use this attribute to let
simulate
and then use vertical-align. Note that when using display:table and display:table-cell, the former must be set on the parent element, and the latter must be set on the child element, so we need to add another
element for the text that needs to be positioned:

div#wrap {   
height:400px;   
display:table;   
}   
div#content {   
vertical-align:middle;   
display:table-cell;   
border:1px solid #FF0099;   
background-color:#FFCCFF;   
width:760px;   
}  
Copy after login

 

<!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#wrap {
    height:400px;
    display:table;
    }
    div#content {
    vertical-align:middle;
    display:table-cell;
    border:1px solid #FF0099;
    background-color:#FFCCFF;
    width:760px;
    }
  </style>
</head>
<body>
  <div id="wrap">
    <div id="content"><br />      <pre class="brush:php;toolbar:false"><br />        现在我们要使这段文字垂直居中显示! 
        div#wrap {
        height:400px;
        display:table;
        }
        div#content {
        vertical-align:middle;
        display:table-cell;
        border:1px solid #FF0099;
        background-color:#FFCCFF;
        width:760px;
        }
      

    
  
Copy after login

This method should be ideal, but unfortunately Internet Explorer 6 does not correctly understand display:table and display:table-cell, so this method is invalid in Internet Explorer 6 and below. Well, that’s depressing! But we have other options.

4. Solution in Internet Explorer

In Internet Explorer 6 and below, there is a flaw in height calculation. After positioning the parent element in Internet Explorer 6, if the percentage calculation is performed on the child element, the calculation basis seems to be inherited (if the positioning value is an absolute value, there is no such problem, but using the percentage calculation basis will It is no longer the height of the element, but the positioning height inherited from the parent element).

For example, we have the following (X)HTML code snippet:

 

<div id="wrap">  
    <div id="subwrap">  
        <div id="content">  
        </div>  
    </div>
</div>        
Copy after login

If we absolutely position the subwrap, then the content will also inherit this attribute. Although it will not be displayed immediately on the page, if you position the content relatively, you will use 100% The ratio will no longer be the original height of content. For example, if we set the position of subwrap to 40%, if we want the upper edge of the content to coincide with the wrap, we must set top:-80%; then, if we set the top:50% of subwrap, we must Use 100% to return the content to its original position, but what if we also set the content to 50%? Then it's exactly vertically centered. So we can use this method to achieve vertical centering in Internet Explorer 6:

div#wrap {   
border:1px solid #FF0099;   
background-color:#FFCCFF;   
width:760px;   
height:400px;   
position:relative;   
}   
div#subwrap {   
position:absolute;   
border:1px solid #000;   
top:50%;   
}   
div#content {   
border:1px solid #000;   
position:relative;   
top:-50%;   
}
Copy after login

Of course, this code will only work in browsers with computing problems such as Internet Exlporer 6. (But I don’t understand. I checked a lot of articles. I don’t know if it’s because they come from the same source or for some other reason. It seems that many people are unwilling to explain the principle of this bug in Internet Exlorer 6. I only have a superficial understanding of it, and I still have to explain it. Further study)

<!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#wrap {
      border:1px solid #FF0099;
      background-color:#FFCCFF;
      width:760px;
      height:400px;
      position:relative;
    }
    div#subwrap {
      position:absolute;
      top:50%;
    }
    div#content {
      position:relative;
      top:-50%;
    }
  </style>
</head>
<body> 
  <div id="wrap">
    <div id="subwrap">
      <div id="content"><pre class="brush:php;toolbar:false">现在我们要使这段文字垂直居中显示!
        div#wrap {
          border:1px solid #FF0099;
          background-color:#FFCCFF;
          width:760px;
          height:500px;
          position:relative;
        }
        div#subwrap {
          position:absolute;
          border:1px solid #000;
          top:50%;
        }
        div#content {
          border:1px solid #000;
          position:relative;
          top:-50%;
        }<br />        
      
    
   
Copy after login

五、完美的解决方案

  那么我们综合上面两种方法就可以得到一个完美的解决方案,不过这要用到CSS hack的知识。

div#wrap {   
display:table;   
border:1px solid #FF0099;   
background-color:#FFCCFF;   
width:760px;   
height:400px;   
_position:relative;   
overflow:hidden;   
}   
div#subwrap {   
vertical-align:middle;   
display:table-cell;   
_position:absolute;   
_top:50%;   
}   
div#content {   
_position:relative;   
_top:-50%;   
}
Copy after login

    至此,一个完美的居中方案就产生了。

<!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#wrap {
      display:table;
      border:1px solid #FF0099;
      background-color:#FFCCFF;
      width:760px;
      height:400px;
      _position:relative;
      overflow:hidden;
    }
    div#subwrap {
      vertical-align:middle;
      display:table-cell;
      _position:absolute;
      _top:50%;
    }
    div#content { 
      _position:relative;
      _top:-50%;
    }
  </style>
</head>
<body>
  <div id="wrap">
    <div id="subwrap">
      <div id="content"><br />        <pre class="brush:php;toolbar:false">现在我们要使这段文字垂直居中显示!
          div#wrap {
            border:1px solid #FF0099;
            background-color:#FFCCFF;
            width:760px;
            height:500px;
            position:relative;
          }
          div#subwrap {
            position:absolute;
            border:1px solid #000;
            top:50%;
          }
          div#content {
            border:1px solid #000;
            position:relative;
            top:-50%;
          }<br />        
      
    
  
Copy after login

  PS:垂直居中vertical-align的值是middle,而水平居中align的值是center,虽然同是居中但关键字不同。

六、实测可以完美实现各种浏览器兼容的居中方案 

    下面这段代码经过实测,可以完美兼容IE7以上的IE浏览器,其它标准浏览器如火狐、谷歌等也没有问题。

说明:尽管有CSS的vertical-align特性,但是并不能有效解决未知高度的垂直居中问题(在一个DIV标签里有未知高度的文本或图片的情况下)。标准浏览器如Mozilla, Opera, Safari等.,可将父级元素显示方式设定为TABLE(display: table;) ,内部子元素定为table-cell (display: table-cell),通过vertical-align特性使其垂直居中,但非标准浏览器是不支持的。非标准浏览器只能在子元素里设距顶部50%,里面再套个元素距顶部-50% 来抵消。

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>水平垂直居中</title>
  <style type="text/css">
    body {padding: 0; margin: 0;}
    body,html{height: 100%;}
    #outer {height: 100%; overflow: hidden; position: relative;width: 100%;}
    #outer[id] {display: table; position: static;}
    #middle {position: absolute; top: 50%;} /* for explorer only*/
    #middle[id] {display: table-cell; vertical-align: middle; position: static;}
    #inner {position: relative; top: -50%;margin: 0 auto;} /* for explorer only */
    div.greenBorder {width:500px;height:584px;background:#333;}
    *+html #outer[id]{position: relative;}
    *+html #middle[id]{position: absolute; }
  </style>
</head>

<body>
  <div id="outer">
    <div id="middle">
      <div id="inner" class="greenBorder">
      </div>
    </div>
  </div>
</body>
</html>
Copy after login

  以上CSS代码的优点是没有hacks,采用了IE不支持的CSS2选择器#value[id]。

CSS2选择器#value[id]相当于选择器#value,但是Internet Explorer不支持这种类型的选择器。同样地.value[class],相当于.value,这些只有标准浏览器能读懂。

测试:Firefox1.5、Opera9.0、IE6.0、IE5.0通过。上面的代码不支持IE7,还需要在最下面加二句:

*+html #outer[id]{position: relative;}

*+html #middle[id]{position: absolute; }
Copy after login

  

 

  

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1234
24
Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative Overview HTML vs. CSS vs. JavaScript: A Comparative Overview Apr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

See all articles