首页 > 其他 > 详细

水平垂直居中

时间:2020-09-01 10:57:31      阅读:48      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

    <div class="box">
        <text class="info">123</text>
        <div class="info"></div>
    </div>
  1. 已知盒子大小: 1) 子盒子:定位+margin

    (position: absolute; left:50%; top:50%; margin-top:-盒子高度一半px;margin-left:-盒子宽度一半px)

     

     .box{
            width: 500px;
            height: 500px;
            background: rgb(216, 185, 185);
            position: relative; 
    
        }
        .info{
            width: 120px;
            height: 120px;
            background: rgb(187, 240, 209); 
            position: absolute; 
            left: 50%;
            top: 50%; 
            margin-top: -60px;
            margin-left: -60px; 
        }
    

    2) 子盒子:定位:

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

     .box{
            width: 500px;
            height: 500px;
            background: rgb(216, 185, 185);
            position: relative; 
    
        }
        .info{
            width: 120px;
            height: 120px;
            background: rgb(187, 240, 209);
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto; 
        }
    
    

     

  2. 未知盒子大小:定位+transform

    (left:50%;top:50%;transform: translate(-50%,-50%))

     

        .box{
            width: 500px;
            height: 500px;
            background: rgb(216, 185, 185);
            position: relative; 
        }
        .info{
            width: 120px;
            height: 120px;
            background: rgb(187, 240, 209); 
            position: absolute; 
            left: 50%;
            top: 50%; 
            transform: translate(-50%,-50%) 
        }
    

     

  3. flex布局: 父盒子

    display:flex; justify-content: center; aligin-items: center;

        .box{
            width: 500px;
            height: 500px;
            background: rgb(216, 185, 185);
            display: flex;
            justify-content: center;
            align-items: center; 
        }
        .info{
            width: 120px;
            height: 120px;
            background: rgb(187, 240, 209);
        }
    

     

  4. 父盒子:仅用于行内块元素

    display: table-ceil; text-align: center; vertical-align: middle;

        .box{
            width: 500px;
            height: 500px;
            background: rgb(216, 185, 185);
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
        <div class="box">
            <text class="info">123</text>
        </div>
    

    技术分享图片

  5. 使用js获取到盒子的宽高,按照方法1设置 定位+margin

 

水平垂直居中

原文:https://www.cnblogs.com/dudududadada/p/13594270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!