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
原文地址:https://www.cnblogs.com/shih/p/7285897.html