search
HomeWeb Front-endHTML TutorialThe N-in-one way to vertically center content using CSS. _html/css_WEB-ITnose

Everyone is familiar with the method of using css div to center the page content horizontally, but how to center the content vertically?

OK, let’s get to the point. Why don’t we use the idea we often use when doing high school math problems: discuss on a case-by-case basis.

1. When the height and width of the DIV to be vertically centered are known:

 1.1 Absolute positioning method:

<strong> CSS: </strong>

    .middle-div{           width:300px;           height:200px;           position:absolute;           left:50%;           top:50%;           margin:-100px 0 0 -150px      }     .parent-div{          position:relitive;     }

html:

    <div class="parent-div">        <div class="middle-div">            <p>我是个高度已知的DIV,我里面的内容可以垂直+水平居中吗?</p>        </div>    </div>
This method achieves both horizontal and vertical centering. However, there are many limitations. The most obvious flaw is the use of absolute positioning. The centered DIV is out of flow layout. Therefore, this method is often used when popping up a centered panel. It is used with jquery:

  >

CSS:

    $(".mydiv").css({               position: "absolute",                left: ($(window).width() - $(".mydiv").outerWidth())/2,                top: ($(window).height() - $(".mydiv").outerHeight())/2     });  

   html:

                                                                                                             by >

1.3 margin:auto method

CSS:

    .floater{        float:left;        height:50%;        margin-bottom:-120px;    }    .middle-div{        clear:both;        height:240px;        position:relitive;        background:#eee;    }


    <div class="floater"></div>    <div class="middle-div"></div>
html:

This method is relatively simple, but unfortunately it is invalid under IE6-7.

    #content {        position:absolute;        top:0;        bottom:0;        left:0;        right:0;        margin:auto;         height:240px;         width:70%;          background:#eee;    }        

 <div id="content"> </div>


<strong>2.当待垂直居中的对象为单行文本或图片,高宽未知时(line-height法):</strong>
 大家公认的最简洁有效的方法:设置容器height与line-height相等,另外,加上overflow:hidden防止意外发生(此处指的容器内字体大于容器高度时的意外)。<strong>  CSS:  </strong>

    p.middle-p{            font:bold 12px/24px Helvertica,Arial,sans-serif;        overflow:hidden;    }     .demo{        height:24px;        color:#fff;        background:#a5a5a5;        font:bold 12px Helvertica,Arial,sans-serif;    }

 

<strong>  html:  </strong>

    <p class="demo middle-p">        文本垂直在P中居中。去掉class中的”middle-p“,再看看效果是什么?添上”middle-p“设置字体大小为30px,看看有什么效果,去掉overflow之后呢?    </p>    

 

 该方法的缺点是只支持单行,且当<p>中为纯文字时,兼容各浏览器;当<P>中只有图片时,IE7+可使图片垂直居中。然而在FF,chrome和IE6均无效;当<p>中有图片和文字时,在IE6中无效,在IE7+,FF,Chrome下有效。
     让我们试着解决只有图片时,在FF,Chrome等现代浏览器下无效的情况,在上述CSS中增加:
<strong>  CSS:</strong>

    p:after{        content:',';        font-size:1px;        visibility:hidden;                   }

 
 
<strong>  html:    </strong>

    <p class="demo middle-p">        <img  src="/static/imghwm/default1.png"  data-src="http://img.sootuu.com/vector/2006-4/2006419181421600.jpg"  class="lazy" height="12px"    style="max-width:90%" alt="The N-in-one way to vertically center content using CSS. _html/css_WEB-ITnose" >    </p>

 
 
     OK!只有图片时在FF,Chrome下也可以垂直居中了!
<strong>3.当待垂直居中的对象为多行文本或其它,高宽未知时:</strong><strong>  3.1当容器高度不固定时(padding法):</strong>
<strong>  为容器添加CSS</strong>:    

    .middle-div{          padding:20px 5px;          background:#eee;     }

 
<strong> html:    </strong>

    <div class="middle-div">        <p>你好,我在DIV中垂直居中。</p>        <p>你好,我在DIV中垂直居中。</p>        <p>你好,我在DIV中垂直居中。</p>        <p>你好,我在DIV中垂直居中。</p>    </div>    <div class="middle-div">        <img  src="/static/imghwm/default1.png"  data-src="http://img.sootuu.com/vector/2006-4/2006419181421600.jpg"  class="lazy" alt="The N-in-one way to vertically center content using CSS. _html/css_WEB-ITnose" >    </div>

 

 使容器padding上下相等,这是最简单的一种方法。支持各浏览器。 <strong>  3.2当容器高度固定时(display:table-cell法):</strong>
     你仍然可以使用padding,不过你需要清楚知道内容的高度和精确的数学计算...这显然是不可取的。
     那么当容器高度固定,待垂直居中的内容又是多行时,该如何去做呢?
     一种有效的做法是将容器display:table-cell,然后使用td,th,caption等标签专有属性:vertical-align:middle;
<strong> CSS:   </strong>

    .middle-div{          display:table-cell;          vertical-align:middle;          height:500px;          background:#eee;     }

 
<strong> html: </strong>
  

    <div class="middle-div">          <p>我想垂直居中,在一个固定高度的DIV中,可以吗?</p>          <p>我想垂直居中,在一个固定高度的DIV中,可以吗?</p>          <p>我想垂直居中,在一个固定高度的DIV中,可以吗?</p>     </div>

 
     Great!在IE8+,FF,Chrome下确实有效。遗憾的是IE6-7仍然无法垂直居中,因为IE6-7并不认识:table-cell属性,将其自动忽略了。
     也许你会想使用table布局,这样不就可以兼容IE6-7了吗。不要试图这样做,因为使用table进行页面布局早已不被赞成。html标签是负责语义的,而不是样式。不要灰心,想让内容在IE6-7下垂直居中不妨试试这种方法:
 
<strong> CSS: </strong>
 html:
  

    .parent{          height:500px;          position:relative;          background:#eee;     }     .sub-parent{          position:absolute;          top:50%;          }     .middle-div{          position:relative;          top:-50%;     }

 
<strong> html: </strong>
  

    <div class="parent">          <div class="sub-parent">               <div class="middle-div">                    <p>我能垂直居中吗?</p>                    <p>我能垂直居中吗?</p>                    <p>我能垂直居中吗?</p>               </div>          </div>     </div>

Since display: inline-block is used, it is not compatible with IE6-7.

 
     让人心塞的是这种方法只在IE6-7下可行,在IE8+以及FF等现代浏览器下效果反而差强人意。为什么呢?是middle-div的top:-50%出了问题。由于父容器的高度根据子容器高度计算出来的,导致-50%无效。可能的解决办法:middle-div的top:-(使用JS得出sub-parent的高度/2)px.
     如果你了解一些CSS hack的技巧,结合上面的display:table-cell方法,那么一个完美的垂直居中方案将会诞生:
<strong> html与上一致; </strong>
<strong> CSS:    </strong>

    .parent{          height:500px;          display:table-cell;          vertical-align:middle;          *position:relative;          background:#eee;     }     .sub-parent{          *position:absolute;          *top:50%;          }     .middle-div{          *position:relative;          *top:-50%;     }

 
 
     在浏览器中看一下效果吧!这个方法看起来还不错,如果非要找一个缺点,那就是DIV嵌套多了一点.
     当允许使用JS时,完全可以动态获得内容的高度,然后结合display:table-cell和margin-top:-(height/2)px来解决。从而避免了多层嵌套.具体方法见1.1<strong>  3.3当容器高度固定时(display:inline-block法)  CSS:  </strong>

    .parent{          height:700px;          border:1px solid #a5a5a5;            text-align:center;        }     .middle-div{          display:inline-block;          width:300px;          vertical-align:middle;          border:1px solid #f00;     }     .parent:before{          content:'';          display:inline-block;          height:100%;          vertical-align:middle;          margin-right:-0.25em;     }

 

Statement
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
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 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.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 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 DesignThe Future of HTML: Evolution and Trends in Web DesignApr 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 OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 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.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools