zoukankan      html  css  js  c++  java
  • CSS中实现水平居中

    [TOCM]

    如果需要居中的元素分别为一下几类:

    1.常规流中 inline 元素,

    • 为父元素设置 text-align: center; 即可实现。

    2.常规流中 block 元素,

    • 1)为元素设置宽度,
    • 2)设置左右 margin 为 auto。
    • 3)IE6 下需在父元素上设置 text-align: center; ,再给子元素恢复需要的值。
    <body>
        <div class="content">
        	aaaaaa aaaaaa a a a a a a a a
        </div>
    </body>
    
    <style>
        body {
            background: #DDD;
            text-align: center; /* 3 */
        }
        .content {
             400px;      /* 1 */
            text-align: left;  /* 3 */
            margin: 0 auto;    /* 2 */
    
            background: orange;
        }
    </style>
    
    aaaaaa aaaaaa a a a a a a a a

    3.浮动元素

    • 1)为元素设置宽度,
    • 2)position: relative;,
    • 3)浮动方向偏移量(left或者right)设置为50%,
    • 4)浮动方向上的margin设置为元素宽度一半乘以-1。
    <body>
        <div class="content">
        aaaaaa aaaaaa a a a a a a a a
        </div>
    </body>
    
    <style>
        body {
            background: #DDD;
        }
        .content {
             400px;         /* 1 */
            float: left;
    
            position: relative;   /* 2 */
            left: 50%;            /* 3 */
            margin-left: -200px;  /* 4 */
    
            background-color: orange;
        }
    </style>
    
    aaaaaa aaaaaa a a a a a a a a

    4.绝对定位元素

    有两种方式设置,其一:

    • 1)为元素设置宽度,
    • 2)偏移量设置为50%,
    • 3)偏移方向外边距设置为元素宽度一半乘以-1
    <body>
        <div class="content">
        aaaaaa aaaaaa a a a a a a a a
        </div>
    </body>
    
    <style>
        body {
            background: #DDD;
            position: relative;
        }
        .content {
             400px;
    
            position: absolute;
            left: 50%;
            margin-left: -200px;
    
            background-color: orange;
        }
    </style>
    
    aaaaaa aaaaaa a a a a a a a a

    其二:

    • 1)为元素设置宽度,
    • 2)设置左右偏移量都为0,
    • 3)设置左右外边距都为auto
    <body>
        <div class="content">
        aaaaaa aaaaaa a a a a a a a a
        </div>
    </body>
    
    <style>
        body {
            background: #DDD;
            position: relative;
        }
        .content {
             400px;
    
            position: absolute;
            margin: 0 auto;
            left: 0;
            right: 0;
    
            background-color: orange;
        }
    </style>
    
    aaaaaa aaaaaa a a a a a a a a
  • 相关阅读:
    Python中的模块与包
    Mac eclipse找不到source的解决办法
    Git常用命令
    MiniCrowler
    九度题库(所有题目整理,适合计算机考研和面试的人用)
    gtest 安装
    计算广告的相关学习资源
    使用python pylab库 画线
    3到6年的.NETer应该掌握哪些知识?
    迭代器模式的一种应用场景以及C#对于迭代器的内置支持
  • 原文地址:https://www.cnblogs.com/shih/p/7285897.html
Copyright © 2011-2022 走看看