Which element can be used to center the image in css3

王林
Release: 2020-11-12 09:12:40
Original
1495 people have browsed it

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.

Which element can be used to center the image in css3

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

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

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

CSS:

.container-1 {position: relative;}

.container-1 img{position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto;}
Copy after login

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!

Related labels:
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