Title

CSS实现居中的几种方法

1.flex弹性布局、grid网格布局实现居中(可能存在浏览器兼容性问题)

可以将justify-content: center; align-items: center;简写为:place-items:center;

place-items是两者的复合属性,接收两个参数,第一个是align-items,第二个是justify-content,如果只写一个参数则表示两个属性相同。

<div class="parent">
    <div class="child"></div>
</div>

<style>
    .parent {
        width: 300px;
        height: 200px;
        background: rgb(203, 192, 255);
        display: flex; //display: grid;父元素设置为flex布局或grid布局 
        justify-content: center; //水平居中
        align-items: center; //垂直居中
    }
    .child {
        width: 50px;
        height: 50px;
        background: rgb(62, 57, 24);
    }
</style>

2.父元素设置flex,子元素设置margin:auto;(最简单)

<div class="parent">
    <div class="child"></div>
</div>

<style>
    .parent {
        width: 300px;
        height: 200px;
        background: purple;
        display: flex;
    }
    .child {
        width: 50px;
        height: 50px;
        background: red;
        margin: auto; //水平垂直居中
    }
</style>

3.父元素相对定位,子元素绝对定位,设置top、left属性的百分比和transform位移属性。

top、left属性的百分比:相对于父级的宽高来进行计算,如果只设置这两个值为50%,那么子级的左上角会和父级的中心点对齐。

进一步操作css3中的位移属性:根据自身来计算百分比,把自身再往左上角各移动50%就实现了子级在父级中水平垂直居中。

<div class="parent">
    <div class="child"></div>
</div>
<style>
    .parent {
        width: 300px;
        height: 200px;
        background: rgb(203, 192, 255);
        position: relative; //相对定位
    }
    .child {
        width: 50px;
        height: 50px;
        background: rgb(221, 201, 73);
        position: absolute; //绝对定位
        left: 50%; //设置距父级左边50%距离
        top: 50%; //设置距父级顶边50%距离
        transform: translate(-50%,-50%); //向左向上平移自身50%距离
    }
</style>

 

posted @ 2023-04-19 15:12  clutch-man  阅读(465)  评论(0)    收藏  举报