How does CSS center the DIV layer?

Source: Internet
Author: User

How to center a div
The main style definition is as follows:

Body {text-align: center ;}
# Center {margin-Right: auto; margin-left: auto ;}
Note:

First, define text-align: center in the parent element. This means that the content in the parent element is centered. for IE, this setting is enough. However, it cannot be centered in Mozilla. The solution is to add "margin-Right: auto; margin-left: auto;" when the sub-element is defined ;"

It should be noted that, if you want to use this method to center the entire page, it is recommended that you do not set it in one Div. You can split multiple divs in sequence, you only need to define margin-Right: auto; margin-left: auto; in each split Div.

How to vertically center an image in a div
Use the background method. Example:

Body {Background: URL (http://www.w3cn.org/style/001/logo_w3cn_194x79.gif) # fff no-repeat center ;}
The key is the final center. This parameter defines the image position. It can also be written as "top left" (upper left corner) or "bottom right", or "50 30"

The effect is as follows:

How to vertically center text in a div
If it is text, you cannot use the background method, you can use the method of increasing the line spacing to work around vertical center, completeCodeAs follows:

<HTML>
<Head>
<Style>
Body {text-align: center ;}
# Center {margin-Right: auto;
Margin-left: auto;
Height: 200px;
Background: # f00;
Width: 400px;
Vertical-align: middle;
Line-Height: 200px;
}
</Style>
</Head>
<Body>
<Div id = "center"> <p> test content </P> </div>
</Body>
</Html>
Note:

Vertical-align: middle; indicates vertical center in the row. We will increase the line spacing to the same height as the entire Div line-Height: 200px; then insert the text to the vertical center.

Related Article

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.