【CSS】不知道图片大小的时候,使用position进行水平和垂直居中

使用position进行定位

    <style>
        .bg {
            background: linear-gradient(#FFDDE1, #FFDDE1);
            width: 100%;
            height: 100%;
            text-align: center;
            position: relative;
        }
        .bg-img {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }
    </style>
    <div class="bg">
        <img src="../img/bg.png" alt="background" class="bg-img">
    </div>

父级元素 div.bg 属性为

position:relative; 
text-align:center;

元素img.bg-img 属性为

position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Sonnenlicht77/article/details/103912997