Turn CSS production horizontal vertical center alignment various methods summary

Source: Internet
Author: User

As the front-end siege division, in the production of Web pages have encountered CSS production horizontal vertical Center, I think we have studied or written, especially the vertical center, but also let people worry. During this time, I have collected several different ways to make vertical centering method, but each method has its own merits, it is not easy to choose the right choice. I will introduce some of these methods to you for your reference. Perhaps for beginners like me to have some help.

Using CSS to achieve the vertical centering of elements is a chore, although there are many ways to implement them, but there are a number of things that might not work properly under some browsers. Let's take a look at the advantages and disadvantages of these different approaches for vertical centering.

Method One:

This method is used to achieve a single-line vertical centering is quite simple, you just have to ensure that the element content is a single line, and its height is fixed, you just set its "line-height" as the "height" value is OK. However, this method is too restrictive and only applies to elements of a single line of text, so this method cannot be used in multiline elements.

Html Markup

<div class= "Vertical" >content</div>

CSS Code:

. vertical {height:100px; line-height:100px;}

Advantages:

Suitable for all browsers, when there is not enough space, the content will not be cut off

Disadvantages:

Only applies to text and pictures, and this method, when you are not a single line, the effect is very poor, poor to make you feel nauseous.

This method is useful for using small elements, such as having a button, a picture, or a single line of text fields.

Method Two:

This method will set absolute positioning (Position:absolute) on the container, and the positioning height (top:50%) and margin-top are half the height (MARGIN-TOP:-HEIGHT/2). This means that using this method to achieve a vertical centering effect, the element must have a fixed height. In this way, you set a fixed height for the element, and if you set it to "Overflow:auto" again, then when the element content exceeds the container, the element will scroll, not the height of the content itself.

HTML Markup

<div class= "Vertical" >content</div>

CSS Code

. vertical {height:100px; position:absolute; top:50%; Margin-top: -50px;}

Advantages:

Able to work in various browsers, simple and straightforward structure, no need to add additional tags

Disadvantages:

Due to the height of the fixed dead element, there is no space for the foot, when the content exceeds the size of the container, either a message or a scrollbar (if the element is inside the body, the body scroll bar will not appear when the user shrinks the browser window).

This method is mainly for the multi-line element to the vertical center of the element, rather than the content of this element is vertically centered, this is to understand and separate clearly. In addition, this method is implemented by absolute positioning, so it is necessary to pay attention to the following points in order to realize the vertical center of the element: one element is related to a relative positioning reference, so to ensure that the element is relative to which is the reference coordinate In addition, you need to set the margin-top for the element to determine a height value and set a negative value for the element, and the values are half the height of the element . Here I suggest that you set a width value for the element, because the element is absolutely positioned and out of the document stream, its width is calculated based on the width of the element content, which makes it visually better, preferably defining a width value for the element.

With this approach, we can make the element not only vertically centered, but also horizontally centered, such as:

HTML Markup

<div id= "Wrap" >test</div>

CSS Code

#wrap {width:200px; height:200px; position:absolute; left:50%; Margin-left: -100px; top:50%; Margin-top: -100px;}

This method can achieve the horizontal vertical center of the element, often used in the layout of the most middle of the page, use this method must be grasped: Horizontal vertical center of the element to have a clear size (in other words, to have the exact width and height value), absolute positioning of the element, and set the Left,top value of "50% "(This is best used for positioning, if only horizontally centered, here you can change relative positioning), and finally set the negative values of margin-top and Margin-left, and the value is half the height and width of the element, respectively .

Method Three:

The third method is to use the div to simulate the table effect, that is, to set the "display" property of multiple <div> to "table" and "Table-cell", and set their "Vertical-align" property value to "middle". For more information about "display:table" You can click here or read Quirksmode's "The display Declaration" article.

HTML Code

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

CSS Code

#container {height:300px; display:table;} #content {Display:table-cell; vertical-align:middle;}

Advantages:

This method does not have the same height limit as the previous two methods, this method can be changed according to the content of the element dynamic height, so there is no space constraints, the content of the element is not due to lack of space to be cut off or appear ugly scroll bar.

Disadvantages:

What are the deficiencies? This method is only suitable for modern browsers and does not work properly under ie6-7, and the structure is more complex than the previous two.

This method is very convenient under the modern browser. But in ie6-7 is not supported, because display:table in ie6-7 is not supported, then in order to solve this method in ie6-7 compatibility, need to add a div, and use hack, let's look at its solution.

HTML Markup

<div class= "Table" > <div class= "TableCell" > <div class= "Content" >content</div> </div> </div>

CSS Code

. table {height:300px; width:300px; display:table; position:relative; float:left;}. TableCell {Display:table-cell; Vertical-align:middle; Text-align:center; padding:10px; *position:absolute; *top:50%; *left:50%; }. content {*position:relative; *top: -50%; *left:-50%;}
Method Four:

This method is a little new, in this way you need to put an empty <div> in front of the center element (block elements can), and then set the height of the <div> is 50%,margin-bottom for the height of the element is half, and the center element needs to clear the float. It should be noted that using this method, if your center element is in the body, you need to give Html,body a "height:100%" attribute.

HTML Markup

<body> <div id= "Floater" ><!--this block has empty content--></div> <div id= "Content" > Content section</div> </body>

CSS Code

html,body {height:100%;} #floater {float:left; height:50%; Margin-bottom: -120px;} #content {clear:both; height:240px; position:relative; }

Advantages:

This method can be compatible with all browsers, without the space, the content will not be cut off

Disadvantages:

The element height is fixed dead, unable to reach the content adaptive height, if the center element plus the overflow attribute, either the element appears scroll bar, or the element is cut off, and the other is not a disadvantage, it is added an empty tag.

Method Five:

This method and method of using Display:table-cell to achieve the same, but method five is different from this method we need a box-type, to achieve the effect of IE, need to add an upstream tag such as "Span" ( it is best to use inline tags, Do not use block tags, because the use of block labels will have no effect , and the line box type height set to 100%, its implementation principle we can read Zhang Xin Xu-Xin space-xin Life of the "size of the image, multi-line text horizontal vertical center."

HTML Markup

<p class= "Table" > <span class= "TableCell" >centering multiple lines <br>in a block Container.</span > <!--[if LTE IE 7]><b></b><! [endif]--> </p>

CSS Code

<style type= "Text/css" >. Table {border:1px solid orange; display:table; height:200px; width:200px; Text-align: Center }. TableCell {Display:table-cell; vertical-align:middle;} </style> <!--[if LTE IE 7]> <style type= ' text /css "> TableCell {display:inline-block;} b {display:inline-block; height:100%; vertical-align:middle; width:1p X } </style> <! [endif]-->

Advantages:

The advantages and methods of this method are the same, there is no high limit.

Disadvantages:

The bad part is this method in order to make IE run normally, need to add some additional tags, the other is the box type of label types are limited. But it is quite convenient to use.

Method Six:

This method is used by the Display:inline-block, and then with the height of the other element to achieve the center

Html Markup

<div id= "Parent" > <div id= "vertically_center" > <p>i am Vertically centered!</p> </div> <div id= "Extra" ><!--ie comment--></div> </div>

CSS Code

<style type= "Text/css" > HTML, body{height:100%;} #parent {height:500px; border:1px solid red;} #vertically_ce Nter, #extra {display:inline-block; vertical-align:middle;} #extra {height:100%;} </style> <!--[if LT IE 8 ]> <style type= "Text/css" > #vertically_center, #extra {display:inline; zoom:1;} #extra {width:1px;} </s Tyle> <! [endif]-->

Advantages:

Self-adapting height, easy to understand

Disadvantages:

You need to set a height for the element's parent element, which can be a fixed value or a percentage height, plus an additional label to be used as a wireframe type, such as Div#extra, and set its height to 100%. In addition, IE6-7 does not support display:inline-block and needs to write a different style for them.

This is a very interesting approach, but you need to know how to use display. For the operation of this method, you can go to see Jonathan Potter wrote "CSS, Vertical centering".

Method Seven:

This method is centered on multi-line content, and the container height is variable, the method is simple, is to give the same padding value

Html Code

<div class= "Columns" > <div class= "item" >test</div> </div>

CSS Code

. item {padding-top:30px;padding-bottom:30px;}

Advantages:

Works in all browsers, supports all elements, is easy to understand and clearly structured

Disadvantages:

Using this method does not give the container a fixed height, and if the fixed height will not achieve the effect.

Method Eight:

As mentioned earlier, if the element is fixed to a vertical center, it is convenient to implement CSS, but it is tricky for adaptive height. So the seventh way is to introduce you to the method of using jquery

Html Markup

<div class= "Container" > <p>centered in the middle of the page with jquery</p> </div>

CSS Code

. container{Background-color: #338BC7; width:270px; height:150px;}

JQuery Code

$ (document). Ready (function () {$ (window). Resize (the function () {$ ('. Container '). css ({position: ' absolute ', left: ($ ( window). Width ()-$ ('. Container '). Outerwidth ())/2, Top: ($ (window). Height ()-$ ('. Container '). Outerheight ())/2}); }); Initially run the function $ (window). Resize (); });

Advantages:

This method, simple structure, easy to understand, does not require the size of fixed elements. Compatible with each browser.

Disadvantages:

Need to call jquery, if you do not support JS or user-Forbidden JS, then will not work properly, that is the cup.

Above this method to achieve the center layout of the page is very convenient, below I based on the idea and method two write a realization element horizontal vertical center of the small plug-in

JQuery Plugin

(function ($) {$.fn.vhalign = function () {return This.each (function (i) {//Gets the content height of the element var h = Math.ceil ($ (this). Height ()); /outerheight=padding+border+height var oh = Math.ceil ($ (this). Outerheight ()); Obtained margin-top value var mt = Math.ceil (OH/2); Gets the element width var w = Math.ceil ($ (this). width ()); outerwidth=padding+border+width var ow = Math.ceil ($ (this). Outerwidth ()); Obtained margin-left var ml = Math.ceil (OW/2); Implements the element centering effect $ (this). css ({"Margin-top": "-" + MT + "px", "Top": "50%", "Margin-left": "-" + ml + "px", "Left": "50%", "Widt H ": w," height ": H," position ":" Absolute "}); }); }; }) (JQuery);

Html Markup

<div class= "wrap" > <p>test jquery</p> </div>

Next you need to call the jquery plugin you just wrote

<script type= "Text/javascript" src= "Vhalign.js" ></script>

Finally, you need to call this function in Div.wrap

<script type= "Text/javascript" > $ (document). Ready (function () {$ (". Wrap"). Vhalign ();}); </script>

One thing to note here is that if the element is not centered relative to the body, it needs to be positioned relative to its parent element.

Above we have witnessed eight different methods to achieve the vertical center of the effect of the element, below we have a simple look at how to achieve the horizontal center of the element (in fact, there are some effects also achieved horizontal center, you can slowly recall).

Method One:

This method mainly uses the width of the Margin:auto mate element to achieve horizontal centering effect.

Html Markup

<div class= "Horizontal" >content</div>

CSS Code:

. horizontal {width:200px; margin:0 auto;}

Using the above method to achieve a horizontal center element must satisfy two conditions: first , the element needs to have a fixed width value, and the Margin-left and margin-right of the second element must be set to auto, Neither of these conditions has the effect of allowing the element to be centered horizontally . This method uses the horizontal center, supports all browsers to run, therefore he also commonly used to achieve the Web page horizontal Center layout effect, if uses in the layout, needs to pay attention to the effect under IE, in other words, if your Web page does not have the explicit declaration "! DOCTYPE ", then the Internet Explorer will also be in the weird mode of parsing your Web page, the above method will not be able to get your page to be horizontally centered, but you can use the following methods to solve the bug.

Html Code:

<div class= "container" > Page content. ... </div>

CSS Code:

body {text-align:center;}. container {text-align:left; width:960px; margin:0 Auto;}
Method Two:

To achieve a fixed width of the horizontal center, we can also use absolute positioning with negative margin to achieve, the specific code is as follows:

Html Markup

<div class= "Horizontal" >content</div>

CSS Code:

. horizontal {width:960px; position:absolute; left:50%; Margin-left: -480px;}

There are a few things to note about this approach: one is to have a fixed width, the other is to absolutely position the element to be centered, and "left:50%", whose three sets a negative "margin-left" to this element and the value equals half the width, and if the element is not relative to the browser, You also need to set a relative positioning "position:relative" on its parent element.

Method Three:

This method is mainly for single-line text center or the table format described above, the main use is Text-align:center let the element horizontal center

. Testh{text-align:center;}

The above is mainly with you to explore and learn a variety of methods to enable the vertical center of the elements, we can make a slight change in these methods to achieve its horizontal center, so that the element horizontal vertical center of the effect. The implementation of a lot of ways, and they have different, can say they have each good, each has a bad, specifically how to make them more suitable for your practical application, you can carefully compare, I prefer method four, simple, compatibility strong, just need to add an additional label. Having said so much, I hope to help my friends in need.

Turn CSS production horizontal vertical center alignment various methods summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.