首页 > 其他 > 详细

垂直居中的方法

时间:2020-09-28 01:03:33      阅读:39      评论:0      收藏:0      [点我收藏+]

设置上下padding

  <div>
    <span>给父元素设置上下padding相等就能使子元素垂直居中,缺点是父元素不能有固定高度</span>
  </div>
    div {
      width: 200px;
      border: antiquewhite 1px solid;
      padding-top: 50px;
      padding-bottom: 50px
    }

    span {
      font-size: 30px;
    }

缺陷是不能设置height

line-height

  <div>
    <span>行距 = line-height - font-size,缺点是要有足够宽度容纳同一行</span>
  </div>
    div {
      height: 100px;
      /* width: 20px; */
      border: solid 1px #1616;
    }

    span {
      font-size: 20px;
      line-height: 100px;
    }

只能是单行文字

flex

  <div>
    <span>flex垂直需要考虑兼容性</span>
  </div>
    div {
      border: solid 1px #161;
      height: 100px;
      width: 100px;
      display: flex;
      align-items: center;
    }

语法简易好理解,兼容性是个问题

display:table

  <ul>
    <li>主站</li>
    <!-- <li>动漫</li>
    <li>电影</li>
    <li>直播</li> -->
  </ul>
    ul {
      display: table;
      height: 100px;
      width: 600px;
      background: rgb(20, 92, 226);
    }

    li {
      list-style-type: none;
      color: beige;
      display: table-cell;
      vertical-align: middle;
    }

简单,有副作用

display:grid

  <ul>
    <li>主站</li>
    <li>动漫</li>
    <li>电影</li>
    <li>直播</li>
  </ul>
    ul {
      height: 100px;
      background: #c4b7d7;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      align-items: center;
      /* justify-content: center; */
    }

    li {
      list-style-type: none;
      color: beige;
    }

布局很牛,兼容性问题难度高

绝对定位

  <div>
    <span>子绝父相</span>
  </div>
    div {
      position: relative;
      height: 100px;
      background: #161;
    }

    span {
      position: absolute;
      height: 20px;
      background: #000;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -10px);
    }

父相子绝,容易上手,缺点是脱离文档流

display:inline-block

  <div class="main">
    <div class="search">
      <form action="">
        <input type="text" placeholder="找找看">
        <span class="button">search</span>
      </form>
    </div>
  </div>
    div.main {
      background: #161;
      height: 200px;
    }

    div.search {
      display: inline-block;
      /* vertical-align: middle; */
    }

    div.main::after {
      content: "";
      display: inline-block;
      /* background: yellow; */
      height: 100%;
      vertical-align: middle;
    }

伪元素添加空元素,兼容性好,不好理解

垂直居中的方法

原文:https://www.cnblogs.com/zhang-bobo/p/13742432.html

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