• 如何让一个行内元素(如image)在div中居中


    1、第一种:用vertical-align

    vertical-align:middle  是依赖div内子元素最高的行高来实现对某元素居中的,而我们只需要建立一个新元素,给他加上inline-block
    属性 再把他高度设置为100%就行了,在下面的<img>设置vertical-align就生效了
    <div class="method1">
      <span class="tiptop"></span>
      <img class="test" src="img/Dota2.jpg" alt="dota2">
    </div>
    
    
    <style>
    .method1{
      text-align:center;
    }
    .tiptop{
      height:100%;
      display:inline-block;
      vertical-align:middle;
    }
    img{
      vertical-align:middle;
    }
    </style>
    
    

    2、第二种:flex布局(注意浏览器兼容性)

    <div class="method2">
      <img src="img_p1_title.png">
    </div>
    
    
    <style>
    .method2 {
      display: flex;
      justify-content: center;  //弹性盒子对象在主轴上的对齐方式
      align-items: center;      //定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。
      background-color:#00a0e9;
      height:200px;
    }
    .method2 img {
      20px;
      height:30px;
      background-color:#0A58A0;
    }
    </style>

    3、绝对定位的方式

    <div class="method3">
      <span>第三种方法</span>
    </div>
    
    
    
    <style>
    .method3 {
      100%;
      height: 200px;
      font-size: 18px;
      position: relative;
      background-color:#00a2d4;
    }
    .method3 span {
      100px;
      height:100px;
      background-color:#00ACED;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      }
    </style>

    4、使用display:table-cell配合vertical-align:center(淘宝也是这样用的)

    <div class="method4">
      <span>第四种方法</span>
    </div>
    
    
    <style>
    .method4 {
       200px;
      height: 200px;
      vertical-align: middle;
      display: table-cell;  /*只支持IE8+及现代浏览器,与position:absolute;或float:left;属性尽量不一起用*/
      text-align: center;
      background-color:#00ACED;
    }
    .method4{
      100px;
      height:100px;
      background-color:#0A58A0;
    }
    </style>
  • 相关阅读:
    np背包问题【算法:折半枚举】
    数字游戏【后缀积问题,一个数学分析问题】
    bfs求最短路径
    利用费马小定理求逆元
    [蓝桥杯2016初赛]剪邮票【全排列,连通块】
    np背包问题【算法:折半枚举】
    火星救[数学,一点前缀和]
    bfs求最短路径
    检测一个正整数是否是2的N次方
    IIS与asp.net身份认证
  • 原文地址:https://www.cnblogs.com/houchen/p/14510880.html
Copyright © 2020-2023  润新知