How to center the img in css? How to vertically center img? Newbies who have just started using CSS may not be very familiar with it. Let’s summarize how to vertically center img in CSS?
There are many ways to vertically center img, including the following three methods
1. Use flex to vertically center img
In CSS, we can use flex to achieve vertical centering, but flex is not a good method. Many browsers now do not support flex, such as IE8 and 9.
First of all, we need to add a div to the supporting image, and define it with a width of 100px and a height of 100px, and define some basic attributes for it. Among them, we set the display element in the div to flex, and then Add the align-items: center attribute to another one.
css code:
body{ background:#999} .flexbox{width: 300px;height: 250px;background:#fff;display: flex;align-items: center} .flexbox img{width: 100px;height: 100px;align-items: center;}
2. Use display to achieve vertical centering of img
First of all, we need to create a div first, and add a picture to it To set the style of div, we can add a diaplay to the parent of img with the attribute table, and set the display attribute in the div containing the image to table-cell. In fact, all we have to do to achieve centering is to set the div with the image. Just change it to vertical-align: middle; attribute.
css code:
.tablebox{width: 300px;height: 250px;background: #fff;display: table} #imgbox{display: table-cell;vertical-align: middle;} #imgbox img{width: 100px}
3. Use the absolute positioning of the image to achieve
We set the div with the image to have a background, and give Add relative attributes to the parent element of img, add absolute and relative attributes to child elements, and set the top value to 50%. What we need to do now is to set a negative margin-top value for the img element.
css code:
body{background: #ccc;} .posdiv{width: 300px;height: 250px;background: #fff;position: relative; margin:0 auto} .posdiv img{width: 100px;position: absolute;top: 50%;margin-top: -50px;}
We recommend using the third method among the above three methods. The third method has better compatibility and is relatively simple. The focus is on mastering the methods and principles.
The above is the complete introduction to how to vertically center img with css. If you want to know more about CSS3 tutorial, please pay attention to the php Chinese website.
The above is the detailed content of How to vertically center img in css. For more information, please follow other related articles on the PHP Chinese website!