前端面试题:未知宽高的盒子如何实现水平垂直居中

一、子级绝对定位+transform

<style>
        .out {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: blue;
        }
        .in {
           position: absolute;
           left: 50%;
           top: 50%;
           /* transform: translateX(-50%) translateY(-50%); */
           transform: translate(-50%,-50%);
           background-color: pink;

        }
    </style>

<body>
   <div class="out">
       <div class="in">111111111111</div>
   </div>
</body>

    二、 父级flex弹性布局

<style>
        .out {
            width: 400px;
            height: 400px;
            background-color: pink;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .in {
            background-color: blueviolet;
        }
    </style>

<body>
    <div class="out">
        <div class="in">11111111111</div>
    </div>
</body>

三、父级添加table属性,子级添加table-cell

 <style>
        .out {
            display: table;
            width: 500px;
            height: 500px;
            background-color: pink;
        }
        .in {
            /* 这种方式只能让文字或是图片水平垂直居中 */
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            /* 背景色会占掉整个父元素的位置 */
            /* background-color: blue; */
        }
        /*我的图片太大了所以设了宽高限制一下*/
        img {
            width: 100px;
            height: 100px;
        }
    </style>

<body>
    <div class="out">
        <!-- <div class="in">11111111111111</div> -->
        <div class="in"><img src="../img/日落.jpg" alt=""></div>
    </div>
</body>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值