zoukankan      html  css  js  c++  java
  • 【CSS基础】实现 div 里的内容垂直水平居中

     方案一: 所有内容垂直水平居中

      兼容性:IE8+。

         条件:内容宽度和高度可以未知,可以是多行文字、图片、div。

      描述:使用table-cell + vertical-align , html代码见文末。

            .centerDiv {
                width: 800px;
                height: 350px;
                background-color: #00b0f0;
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

    方案二: 单行内容垂直水平居中

      兼容性:IE7+

      条件: 文字内容必须为单行

          描述: text-align: center水平居中, line-height 等于height 垂直居中

    方案三: 未知大小图片垂直水平居中

      兼容性:IE8+

      条件:内容为图片,文字不行。文字和图片组合时,图片能居中,文字不能。

      描述:父节点相对定位,图片绝对定位

            .centerDiv {
                width: 800px;
                height: 350px;
                background-color: #00b0f0;
                position: relative;
            }
    
            .centerDiv img {
                position: absolute;
                left: 0;top:0;right: 0;bottom: 0;
                margin: auto;
            }    

    方案四:已知宽高度div垂直水平居中

      兼容性:I5+

      条件:内容div高度宽度已知

      描述: 定位 + 负margin

            .centerDiv {
                width: 800px;
                height: 350px;
                background-color: #00b0f0;
                position: relative;
            }
    
            .centerDiv div {
                width: 500px;
                height: 300px;
                background-color: #00ee00;
                position: absolute;
                left: 50%; top: 50%;
                margin-left: -250px;
                margin-top: -150px;
            }

    附: html测试代码

         <div class="centerDiv">
            <p>hello, this a p tag.</p>
        </div><br>
    
        <div class="centerDiv">
            <img src="img/head.jpg">
        </div><br>
    
        <div class="centerDiv">
            <div>
                <p>qwe</p>
                <p>qwe</p>
                <p>qwe</p>
            </div>
        </div>
    只有足够努力,才能看起来毫不费力
  • 相关阅读:
    GJM: Unity3D AssetBundle 手记 [转载]
    GJM: Unity3D基于Socket通讯例子 [转载]
    GJM:用C#实现网络爬虫(二) [转载]
    JSONP(跨域请求) —— 一种非官方跨域数据交互协议
    经典布局之圣杯布局 —— 左右定宽,中间流式
    js中的callback(阻塞同步或异步时使用)
    Emmet:HTML/CSS代码快速编写神器
    CSS弹性盒模型 box-flex
    JSON对象的stringify()和parse()方法
    懒加载 lazy load
  • 原文地址:https://www.cnblogs.com/codelovers/p/4399664.html
Copyright © 2011-2022 走看看