zoukankan      html  css  js  c++  java
  • 总结div里面水平垂直居中的实现方法

      最近经常碰到要垂直居中的问题,所以想着总结一下:关于如何设置小盒子在大盒子里面水平垂直方向同时居中的实现方法有很多种,下面仅列举了常用的几种。

      首先看一下要实现的效果图及对应的html代码:

    <div class="parent">
        <div class="child">           
        </div>
    </div>

    1、使用定位的方法

    .parent {
         300px;
        height: 200px;
        border: 1px solid red;
        position:relative;
    }
    .child {
         100px;
        height: 100px;
        border: 1px solid violet;
        position:absolute;
        top: 50%;
        left:50%;
        margin-top: -50px;     /*这里是小盒子高的一半*/
        margin-left: -50px;    /*这里是小盒子宽的一半*/
    }

      还有就是子元素宽高不固定时

    //vertical center
    .vertical-center{
      position absolute
      top 50%
      transform translate(0,-50%)
    }
    .vertical-horizontal{
      position absolute
      left 50%
      top 50%
      transform translate(-50%,-50%)
    }

    2、利用定位及margin:auto实现

    .parent {
         300px;
        height: 200px;
        border: 1px solid red;
        position:relative;
    }
    .child {
         100px;
        height: 100px;
        border: 1px solid violet;
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

      实现原理是设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;

    3、使用display:table-cell;

    .parent {
       300px;
      height: 200px;
      border: 1px solid red;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    .child {
       100px;
      height: 100px;
      border: 1px solid violet;
      display: inline-block;
    }

      实现原理:display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签;组合使用vertical-align、text-align,可以使父元素内的所有行内元素水平垂直居中(也就是将内部的元素设置display:inline-block)

    4、使用伸缩布局display:flex

    .parent {
       300px;
      height: 200px;
      border: 1px solid red;
      display: flex;
      justify-content: center;  /*水平居中*/
      align-items: center;      /*垂直居中*/
    }
    .child {
       100px;
      height: 100px;
      border: 1px solid violet;
    }
  • 相关阅读:
    【Oracle11g】06_网络配置
    【Python3 爬虫】U20_正则表达式爬取古诗文网
    【Oracle11g】05_完整性约束
    【Python3 爬虫】U19_正则表达式之re模块其他函数
    【Python3 爬虫】U18_正则表达式之group分组
    【Python3 爬虫】U17_正则表达式之转义字符和原生字符
    【Python3 爬虫】U16_正则表达式之开始结束和或语法
    常见的概率分布
    广义线性模型
    gamma函数及相关其分布
  • 原文地址:https://www.cnblogs.com/goloving/p/9231672.html
Copyright © 2011-2022 走看看