zoukankan      html  css  js  c++  java
  • HTML/CSS:div水平与元素垂直居中(2)

    单个div水平居中:设置margin的左右边距为自动

    div水平和垂直居中,text-align和vertical-align不起作用,因为标签div没有这两个属性,所以再css中设置这两个值不能居中的效果

    代码:

    HTML

    <div id="parent">
    
    </div>

    CSS

    #parent {
    margin: 0 auto; 
    }

     

    多个div水平居中:设置display的属性为inline-block

    多个div水平居中,text-align和vertical-align不起作用,因为标签div块没有这两个属性,所以需要先使用display进行块级的调整

    代码:

    HTML

    <div class="imgs">
         <div class="img">
            <a><img src=" " /></a>
            <div class="desc">在此处添加对图像的描述</div>
         </div>
                
         <div class="img">
            <a><img src=" " /></a>
            <div class="desc">在此处添加对图像的描述</div>
         </div>
                
         <div class="img">
            <a><img src=" " /></a>
            <div class="desc">在此处添加对图像的描述</div>
         </div>
    </div>

    CSS

    .imgs {
    background-color: #F5F5DC;
    text-align: center;
    }
    
    .img {
    display: inline-block;
    }

    div 元素垂直+水平居中

    利用CSS进行元素的水平居中,比较简单,行级元素设置其父元素的text-align center,块级元素设置其本身的left 和 right margins为auto即可。下列每一种适用于不同的情况,在实际的使用过程中选择某一种方法即可。

     

    1.Line-Height Method 行高法

    适用:单行文本

    代码:

    HTML

    <div id="parent">
    <div id="child">Text here</div>
    </div>

    CSS

    #child {
    text-align: center; /*文字水平居中*/ line-height: 200px; /*文字垂直居中*/ }

    适用:单行图片

    代码:

    HTML

    <div id="parent">
    <img src="image.png" alt="" />
    </div>

    CSS

    #parent {
    text-align: center; /*图片水平居中*/ line-height: 200px; } #parent img { vertical-align: middle; }

     

    2.Table Method 表格法

    适用:通用

    代码:

    HTML

    <div id="parent">
    <div id="child">Content here</div>
    </div>

    CSS

    #parent {
    display: table;
    margin: 0 auto; /*div水平居中*/
    text-align: center; /*内容水平居中*/
    }
    #child {
    display: table-cell;
    vertical-align: middle;
    }

    低版本 IE fix bug 需添加:

    #child {
    display: inline-block;
    }

     

    3.Equal Top and Bottom Padding 内边距法

    适用:通用

    代码:

    HTML

    <div id="parent">
    <div id="child">Content here</div>
    </div>

    CSS

    #parent {
    text-align: center; /*内容水平居中*/ padding: 5% 0; } #child { padding: 10% 0; }
  • 相关阅读:
    汇总sql
    mybatis动态表名
    Windows下PHP(Thread Safe与Non Thread Safe)版本说明
    清除mssql日志
    ISAPI_Rewrite的一些参数
    sublime相关
    php301代码
    【备忘】win7下IIS 用FastCGI模块 配置PHP
    poj 2112 Optimal Milking floyd + 二分 + 最大流
    记录运行时间
  • 原文地址:https://www.cnblogs.com/One-sprite/p/7011337.html
Copyright © 2011-2022 走看看