ITPub博客

首页 > IT职业 > IT生活 > 第19题:让一个div水平垂直居中有几种方式?

第19题:让一个div水平垂直居中有几种方式?

IT生活 作者:lxhit 时间:2021-09-09 08:51:33 0 删除 编辑

图片描述

实现上方效果,下面列举几个常用的方法,个人比较推荐用 flex 布局实现

方式 1(利用 margin 和绝对定位)

html

css

.container {
    position: relative;
    width: 150px;
    height: 150px;
    background-color: #000;

    .box {
        margin: auto;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 50px;
        height: 50px;
        background-color: #fff;
    }
}

方式 2(利用 flex 布局)

html

css

.container {
    position: relative;
    width: 150px;
    height: 150px;
    background-color: #000;
    display: flex;
    justify-content: center;
    align-items: center;

    .box {
        width: 50px;
        height: 50px;
        background-color: #fff;
    }
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4418/viewspace-2796769/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    81
  • 访问量
    621