Home > Web Front-end > CSS Tutorial > How to center photos vertically with css

How to center photos vertically with css

WBOY
Release: 2021-12-02 17:15:15
Original
8022 people have browsed it

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.

How to center photos vertically with css

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>
Copy after login

Output result:

How to center photos vertically with css

##(Learning video sharing:

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!

Related labels:
css
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template