img 实现水平垂直居中

img 元素定义为块元素,并放入弹性盒子容器后,可通过 margin:auto; 样式实现水平和垂直居中,将下面的代码放入body中可以测试效果:

<style>
    div{
        background-color: aquamarine;
        width: 400px;
        height:200px;
        display: flex;  /*定义为弹性盒子容器*/
    }
    img{
        width: 100px;
        height: auto;
        aspect-ratio: 1/1;  /*固定宽高比*/
        display: block;  /*定义为块级元素*/
        margin: auto;
    }
style>

<div>
    <img src="https://profile.csdnimg.cn/E/1/9/3_ymz641">
div>

如需水平居中,可以将 margin: auto;替换为:

margin-left:auto;
margin-right:auto;

同样,如需垂直剧中,可以将 margin: auto;替换为:

margin-top:auto;
margin-bottom:auto;

你可能感兴趣的:(前端,css,css3,html,img)