CSS Production horizontal Vertical center alignment

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

    1. <div class= "Vertical" >content</div>
Copy Code


CSS Code:

    1. . vertical {
    2. height:100px;
    3. line-height:100px;/* value equals the value of the element height */
    4. }
Copy Code


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

    1. <div class= "Vertical" >content</div>
Copy Code


CSS Code

    1. . vertical {
    2. Height of the height:100px;/* element */
    3. Position:absolute;
    4. The position of the top edge of the top:50%;/* element is half the height of the parent element.
    5. Margin-top: -50px;/* set element top negative margin, size is half of the height of the element */
    6. }
Copy Code


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

    1. <div id= "Wrap" >test</div>
Copy Code


CSS Code

    1. #wrap {
    2. Width of the width:200px;/* element */
    3. Height of the height:200px;/* element */
    4. Position:absolute; L
    5. eft:50%;/* with negative values of margin-left to achieve horizontal centering */
    6. Margin-left: The size of the -100px;/* value equals half the width of the element */
    7. top:50%;/* vertical centering with negative values of margin-top */
    8. Margin-top: The size of the -100px;/* value equals half the height of the element */
    9. }
Copy Code


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

    1. <div id= "Container" >
    2. <div id= "Content" >content</div>
    3. </div>
Copy Code


CSS Code

    1. #container {
    2. height:300px;
    3. display:table;/* let elements render in tabular form */
    4. }
    5. #content {
    6. display:table-cell;/* let elements render as a single element of a table */
    7. vertical-align:middle;/* vertical alignment using elements */
    8. }
Copy Code


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

    1. <div class= "Table" >
    2. <div class= "TableCell" >
    3. <div class= "Content" >content</div>
    4. </div>
    5. </div>
Copy Code


CSS Code

    1. . Table {
    2. height:300px;/* height value can not be less than */
    3. width:300px;/* width value can not be less */
    4. display:table;
    5. position:relative; Float:left;
    6. }
    7. . TableCell {
    8. Display:table-cell;
    9. Vertical-align:middle;
    10. Text-align:center;
    11. padding:10px;
    12. *position:absolute;
    13. *top:50%;
    14. *left:50%;
    15. }
    16. . Content {
    17. *position:relative;
    18. *top:-50%;
    19. *left:-50%;
    20. }
Copy Code


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

    1. <body>
    2. <div id= "Floater" ><!--this block has empty content--></div>
    3. <div id= "Content" >content section</div>
    4. </body>
Copy Code


CSS Code

    1. html,body {height:100%;}
    2. #floater {float:left;
    3. height:50%;/* 50%*/relative to the height of the parent element
    4. Margin-bottom: -120px;/* value is half the height of the center element (240PX/2) */
    5. }
    6. #content {clear:both;/* Clear float */
    7. height:240px; position:relative;
    8. }
Copy Code


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 is the same as using Display:table-cell to achieve, but the 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 there is no effect on using the Block label, set the height of the box type to 100%.

HTML Markup

    1. <p class= "Table" >
    2. <span class= "TableCell" >centering multiple lines <br>in a block container.</span>
    3. <!--[If LTE IE 7]><b></b><! [endif]-->
    4. </p>
Copy Code


CSS Code

    1. <style type= "Text/css" >
    2. . Table {
    3. border:1px solid Orange;
    4. display:table;
    5. height:200px; width:200px;
    6. Text-align:center;
    7. }
    8. . TableCell {
    9. Display:table-cell;
    10. Vertical-align:middle;
    11. }
    12. </style>
    13. <!--[If LTE IE 7]>
    14. <style type= "Text/css" >
    15. . TableCell {
    16. Display:inline-block;
    17. }
    18. D =
    19. Display:inline-block;
    20. height:100%;
    21. Vertical-align:middle; width:1px;
    22. }
    23. </style>
    24. <! [endif]-->
Copy Code


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

    1. <div id= "Parent" >
    2. <div id= "Vertically_center" >
    3. <p>i am Vertically centered!</p>
    4. </div>
    5. <div id= "Extra" ><!--ie comment--></div>
    6. </div>
Copy Code


CSS Code

  1. <style type= "Text/css" >
  2. Html
  3. body{
  4. height:100%;
  5. }
  6. #parent {h
  7. eight:500px;/* defines the height so that the wire box type Div#extra has a reference, which can be a fixed value or a percentage */
  8. border:1px solid red;
  9. }
  10. #vertically_center,
  11. #extra {
  12. display:inline-block;/* the element into a inline block display */
  13. vertical-align:middle;/* Vertical Center */
  14. }
  15. #extra {
  16. height:100%; /* Set the box type to the 100% height of the parent element */
  17. }
  18. </style>
  19. <!--[If Lt IE 8]>
  20. <style type= "Text/css" >
  21. /*ie6-7 does not support display:inline-block, so another hack is written in ie6-7 to support ie6-7*/
  22. #vertically_center,
  23. #extra {
  24. Display:inline;
  25. Zoom:1; }
  26. #extra {
  27. width:1px;
  28. }
  29. </style>
  30. <! [endif]-->
Copy Code


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

    1. <div class= "Columns" >
    2. <div class= "Item" >test</div>
    3. </div>
Copy Code


CSS Code

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



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

    1. <div class= "Container" >
    2. <p>centered in the middle of the Page with jquery</p>
    3. </div>
Copy Code


CSS Code

    1. . container{
    2. width:270px;
    3. height:150px;
    4. }
Copy Code


jQuery Code

    1. $ (document). Ready (function () {
    2. $ (window). Resize (function () {
    3. $ ('. Container '). CSS ({
    4. Position: ' Absolute ',
    5. Left: ($ (window). Width ()-$ ('. Container '). Outerwidth ())/2,
    6. Top: ($ (window). Height ()-$ ('. Container '). Outerheight ())/2
    7. });
    8. });
    9. Initial run function
    10. $ (window). Resize ();
    11. });
Copy Code


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

  1. (function ($) {
  2. $.fn.vhalign = function () {
  3. Return This.each (function (i) {
  4. Gets the content height of the element
  5. var h = Math.ceil ($ (this). Height ());
  6. Outerheight=padding+border+height
  7. var Oh = Math.ceil ($ (this). Outerheight ());
  8. Get Margin-top value
  9. var mt = Math.ceil (OH/2);
  10. Get element width
  11. var w = Math.ceil ($ (this). width ());
  12. Outerwidth=padding+border+width
  13. var ow = Math.ceil ($ (this). Outerwidth ());
  14. Get Margin-left
  15. var ml = Math.ceil (OW/2);
  16. Implement element centering effect
  17. $ (this). CSS ({
  18. "Margin-top": "-" + MT + "px",
  19. "Top": "50%",
  20. "Margin-left": "-" + ml + "px",
  21. "Left": "50%",
  22. "width": w,
  23. "Height": H,
  24. "Position": "Absolute"
  25. });
  26. });
  27. };
  28. }) (JQuery);
Copy Code


Html Markup

    1. <div class= "Wrap" >
    2. <p>test jquery</p>
    3. </div>
Copy Code


Next you need to call the jquery plugin you just wrote

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


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

    1. <script type= "Text/javascript" >
    2. $ (document). Ready (function () {
    3. $ (". Wrap"). Vhalign ();
    4. });
    5. </script>
Copy Code


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

    1. <div class= "Horizontal" >content</div>
Copy Code


CSS Code:

    1. . horizontal {
    2. width:200px;
    3. margin:0 Auto;
    4. }
Copy Code



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:

    1. <div class= "container" > Page content. ... </div>
Copy Code


CSS Code:

    1. Body {
    2. text-align:center;/* implement IE in weird Mode page Horizontal Center */
    3. }
    4. . container {
    5. text-align:left;/* to restore text to left alignment */
    6. width:960px;/* Set Page Total width */
    7. margin:0 auto;/* to align the page horizontally */
    8. }
Copy Code



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

    1. <div class= "Horizontal" >content</div>
Copy Code


CSS Code:

    1. . horizontal {
    2. width:960px;
    3. Position:absolute;
    4. left:50%;
    5. Margin-left: -480px;/* This value equals "-WIDTH/2" */
    6. }
Copy Code


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%"; its three sets a negative "margin-left" to this element and the value equals half the width, In addition, 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

    1. . Testh{text-align:center;}
Copy Code


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.

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.