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 ;} |