Home > Article > Web Front-end > How to center photos vertically with css
Method: 1. Add a relative positioning style to the parent element of the photo element, and add an absolute positioning style to the photo element; 2. Use the top attribute and "margin-top" attribute to set the photo to be vertically centered, just give the photo Just add the "top:50%;margin-top:top margin value;" style to the element.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
How to center the photo vertically with css
Use absolute positioning to achieve vertical centering
1. Add to the parent element of img Relative positioning attribute (position: relative), and at the same time, add an absolute positioning attribute (position: absolute) to the child element, that is, the image img element.
2. Set the top attribute of the picture element to 50%.
3. Now we need to set a negative margin-top value for the img element. This value is half the height of the element you want to vertically center. *If you are not sure about the height of the element, you can not use margin. -top, instead use the transform:translateY(-50%); attribute.
Remember: If you want to center horizontally at the same time, you can do it using the same technique you use to center vertically.
The example is as follows:
<html> <head> <style type="text/css"> .posdiv{ width: 300px; height: 250px; position: relative; border:1px solid red; } .posdiv img{ width: 100px; position: absolute; top: 50%; margin-top: -50px; } </style> </head> <body> <div class="posdiv"> <img src="1118.02.png" alt=""> </div> </body> </html>
Output result:
css video tutorial)
The above is the detailed content of How to center photos vertically with css. For more information, please follow other related articles on the PHP Chinese website!