CSS Vertical and horizontal centering

Source: Internet
Author: User

In CSS, the center is used very frequently.

Centered horizontally and vertically

Horizontal centering is simple:

Body {                background:#f90;            }

Body Unity for this color

{                margin:0 Auto;                 background:Green;                 width:10em;                 text-align:center;            }
< Div > </Div>        

Note that width is a must, otherwise if it is a block-level element (DIV) will occupy a row, there is nothing to center, if the inline element (span) will not work, there is no center to say

Effect:

On the vertical center, this is interesting, although the use of not as much as the level, but to use the time is really more complex than the level, according to the CSS authoritative guide in the code (there are changes):

This is the inline element:

b {                position:absolute;                 Left:0;                 Right:0;                 top:0;                 Bottom:0;                 height: 5em;                 margin:auto 0;                 background:silver;            }
< b >Hello World</b>

Effect:

Note: The gray part is vertically centered.

After analysis, these lines are required:

Position:absolute;top:0;bottom:0;height:5em;margin:auto 0;

The first element must be absolute, and then the Top,bottom is set to 0, so that the element cannot be docked on the upper boundary or docked at the lower boundary

In addition note: The vertical centering effect here is actually the user agent (browser) complement the margin to achieve, that is, because, Top,bottom are 0, and the element height only 5em, the browser on its own complement the rest of the blank, is Margin-top, Margin-bottom filled up up and down

Then it corresponds to the horizontal center, the vertical center is the height necessary, otherwise it will be:

Elements are stretched by top and bottom two CSS properties

(same as block-level elements)

CSS Vertical and horizontal centering

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.