In css3, you can use the [align-items:center] element and the [justify-content:center] element to center the image. The align-items property defines the alignment of flex items along the vertical axis of the current row of the flex container.
Method:
Use the two attributes align-items:center (vertical centering) and justify-content:center (horizontal centering) .
The align-items property defines the alignment of flex items in the vertical axis direction of the current row of the flex container.
(Learning video recommendation: css video tutorial)
html:
<div class="container container-2"> <img src="http://scrm-staging-cdn.oss-cn-hangzhou.aliyuncs.com/avatar/wechat/aHR0cDovL3d4LnFsb2dvLmNuL21tb3Blbi9YeFQ5VGlhSjFpYmYzdFk4b2hENHFpYmxkTUdEbk1NRXFuZVdlZk5pY2lic1h1MjFZdHAxV1o2bGsxUTFVeE9vSzY4QVJEa0tRZ05OYWgzeTFzY01YUUp3clBRLzA="> </div>
css:
.container-2 { display: -webkit-box; display: -ms-flexbox; display: flex-box; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack:center; -ms-flex-pack:center; justify-content:center; text-align: center; }
is OK Use absolute positioning Margin to achieve this.
The image floats relative to the outer layer, and then margin: auto
HTML:
<h3 class="demo">绝对定位+Margin</h3> <div class="container container-1"> <img src="http://scrm-staging-cdn.oss-cn-hangzhou.aliyuncs.com/avatar/wechat/aHR0cDovL3d4LnFsb2dvLmNuL21tb3Blbi9YeFQ5VGlhSjFpYmYzdFk4b2hENHFpYmxkTUdEbk1NRXFuZVdlZk5pY2lic1h1MjFZdHAxV1o2bGsxUTFVeE9vSzY4QVJEa0tRZ05OYWgzeTFzY01YUUp3clBRLzA="> </div>
CSS:
.container-1 {position: relative;} .container-1 img{position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto;}
Related recommendations:CSSTutorial
The above is the detailed content of Which element can be used to center the image in css3. For more information, please follow other related articles on the PHP Chinese website!