• 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
  • 相关阅读:
    定义类或对象
    CSS 超出的文字显示省略号(单行、多行)
    获取Json对象的长度以及判断json对象是否为空
    第三次作业附加
    八皇后问题解题报告(dfs
    STL学习笔记(不定期更新)
    寒假作业之三
    寒假作业之二(2)
    寒假作业之二(1)
    第一篇随笔居然是总结耶
  • 原文地址:https://www.cnblogs.com/shih/p/7285897.html
Copyright © 2020-2023  润新知