• 【转载】在不确定自身高度的情况下,用 CSS 实现元素垂直居中的3种方法


    作者:Jaskey Lam
    链接:https://www.zhihu.com/question/20543196/answer/57757836
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    1.不知道自己高度和父容器高度的情况下, 利用绝对定位只需要以下三行:
    1.  
      parentElement{
    2.  
      position:relative;
    3.  
      }
    4.  
       
    5.  
      childElement{
    6.  
      position: absolute;
    7.  
      top: 50%;
    8.  
      transform: translateY(-50%);
    9.  
       
    10.  
      }

    2.若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可

    1.  
      parentElement{
    2.  
      height:xxx;
    3.  
      }
    4.  
       
    5.  
      .childElement {
    6.  
      position: relative;
    7.  
      top: 50%;
    8.  
      transform: translateY(-50%);
    9.  
      }


    demo: Edit fiddle - JSFiddle


    Flex 布局:

    不考虑兼容老式浏览器的话,用Flex布局简单直观一劳永逸:
    1.  
      parentElement{
    2.  
      display:flex;/*Flex布局*/
    3.  
      display: -webkit-flex; /* Safari */
    4.  
      align-items:center;/*指定垂直居中*/
    5.  
      }

    demo: 
     
    作者:李天昭
    链接:https://www.zhihu.com/question/20543196/answer/15432218
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    1. 表格居中
    HTML:
    <div id="box"><div id="content"></div></div>
    CSS:
    #box { display: table; height: 400px; background: #c00; }
    #content { color: #fff; text-align: center; display: table-cell; vertical-align: middle; }
    兼容性:,除了IE6/7都支持


    2. inline-block
    HTML:
    <div id="box">
    <div id="content">我是内容<br />我也是内容</div>
    <div id="actor">我是演员</div>
    </div>
    CSS:
    #box { height: 400px; background: #c00;}
    #content, #actor { display: inline-block; vertical-align: middle;}
    #content { font-size: 12px; color: #fff;}
    #actor {height: 400px; font-size: 0;}
  • 相关阅读:
    ubuntu 更新软件
    如何在linux(lubuntu)下搭建C/C++开发环境
    Linux下如何查看版本信息
    知识点笔记
    Require.js中使用jQuery 插件
    async中常用总结
    node.js在遇到“循环+异步”时的注意事项
    前端性能优化
    生产/消费者问题
    线程与内存
  • 原文地址:https://www.cnblogs.com/ch-zaizai/p/11730835.html
Copyright © 2020-2023  润新知