• 【CSS】4种CSS方法设置元素垂直水平居中


    1. 宽高固定

    设置要水平垂直居中的 div 的 position 为 absolute,left:50%; margin-left为负的这个元素宽度的一半,同理,top:50%;margin-top为负的这个元素的高度的一半。

    #child {
       300px;
       height:200px;
       position:absolute;
       left:50%;
       margin-left:-150px;
       top:50%;
       margin-top:-100px;
    }
    

    2. 宽高不固定

    由 1 可演变,既然 margin-left ,margin-top 为负的这个元素宽度, 高度的一半, 那么也可用百分比设置啊,使用 transform 属性, translate 平移水平、垂直方向的百分值。即

    #child {
       position: absolute;
       left: 50%;
       top: 50%;
       transform: translate(-50%, -50%);
    }
    

      

    3. flex 布局

    还可以用 flex 布局哦~ 仅需要父级元素配置就好了~

    #parent {
      display: flex;
      justify-content: center;
      align-items:center;        
    }
    

      

    4.margin auto 布局

    #box {
                 300px;
                height: 200px;
                position: relative;
                background-color: aqua;
            }
            #inner {
                position: absolute;
                 50px;
                height: 50px;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                margin: auto;
                background-color: brown;
            }

    活久见

     由此,便可以实现子元素的上下左右居中的效果,快去试试把~

  • 相关阅读:
    FuelPHP 系列(三) ------ Model 模型
    FuelPHP 系列(二) ------ route 路由
    FuelPHP 系列(一) ------ Oil 命令
    微信小程序初探
    基于 Laravel 的 文件管理
    laravel(一)
    Git从零开始(三)
    Git从零开始(二)
    Git从零开始(一)
    Linux服务器学习(二)
  • 原文地址:https://www.cnblogs.com/xiabaoying/p/6516685.html
Copyright © 2020-2023  润新知