Css achieves horizontal vertical center in div and horizontal center in image

Source: Internet
Author: User

Perfect solution for div center! (Center horizontally and vertically)


1. Use css for centering:

The code is as follows: Copy code
Position: fixed; left: 50%; top: 50%; margin-left: width/2; margin-top: height/2;
For ie6, you can only change position: to absolute;

Center the image in the div

Use the margin attribute of the image to center the image horizontally, and use the padding attribute of the div to center the image vertically.

Method 1:
The css code is as follows:

The code is as follows: Copy code

Div {width: 300px; height: 150px; background-color: # eee; padding-top: 50px; border: #000 1px solid ;}

Img {display: block; margin: 0 auto ;}

Note:

Img is an inline element. To set its margin attribute to center it, you need to convert it into a block element display: block, and then use margin: 0 auto; to realize horizontal center of the image; (Some designers add a div label to the image and use the margin of the div label to center the image.


Idea: use the text-align attribute to center the image horizontally and set the value of padding-top to center it vertically.

Method 2:

The css style is as follows:

The code is as follows: Copy code

Div {width: 300px; height: 150px; background-color: # ccc; border: #000 1px solid; text-align: center; padding-top: 50px ;}

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.