【持续更新】CSS居中

水平垂直居中

  • 知道自身的宽度、高度
<div class="test"></div>
<style>
    .test {
        position: absolute;
        height: 200px;
        width: 200px;
        left: 50%; /* 父级宽度的50% */
        top: 50%; /* 父级高度的50% */
        margin-left: -100px;
        margin-top: -100px;
        border: 1px solid #000000; /* 方便看效果 */
    }
</style>

原理:先水平、垂直定位到父级的中间(父级宽度和高度的一半),再向左、上平移自身宽度、高度的一半,即可完成水平、垂直居中。

  • 不知道自身的宽度、高度
<div class="test"></div>
<style>
    .test {
        position: absolute;
        height: 200px;
        width: 200px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        border: 1px solid #000000; /* 方便看效果 */
    }
</style>

原理:同上一种方法一样,先水平、垂直定位到父级的中间(父级宽度和高度的一半),再向左、上平移自身宽度、高度的一半,而translate里面是自身的百分百,所以不需要知道自身的宽度。

posted @ 2019-03-19 09:42  lipohong  阅读(112)  评论(0编辑  收藏  举报