CSS-水平居中的方法

87 阅读1分钟

直接上代码了;不多说!!!

css代码

      * {
            margin: 0;
            padding: 0;
        }
        /* 方法一: 文本元素直接使用text-align实现水平居中 */
        .container1 {
            height: 30px;
            text-align: center;
            background-color: antiquewhite;
        }

        /* 方法二: 使用margin:0 auto实现水平居中 */
        .container2 {
            text-align: center;
            margin-top: 10px;
        }

        .container2 .element {
            margin: 0 auto;
            background-color: antiquewhite;
        }

        /* 方法三:使用position:定位加 margin负值实现水平居中 */

        .container3 {
            position: relative;
            background-color: antiquewhite;
            height: 20px;
            margin-top: 10px;
        }

        /* 有一点不好,前提得知道自身的宽度,下面的方法不需要知道宽度 */
        .container3 .element {

            width: 280px;
            background-color: blue;
            text-align: center;
            position: absolute;
            margin-left: -140px;
            left: 50%;
            color: white;
        }

        /* 方法四:使用position+transform */
        .container4 {
            height: 20px;
            margin-top: 10px;
            position: relative;
            background-color: antiquewhite;
        }

        /* 但是可能存在兼容性问题,且里面的像素可能会出现羽化效果 */
        .container4 .element {
            background-color: blue;
            color: white;
            position: absolute;
            width: 200px;
            text-align: center;
            left: 50%;
            transform: translateX(-50%);
        }

        /* 方法五:使用flex */
        .container5 {
            display: flex;
            justify-content: center;
            height: 20px;
            margin-top: 10px;
            background-color: antiquewhite;
        }

        .container5 .element {
            background-color: blue;
            color: white;
        }
   

下面是html代码:

  <div class="container1">
        container1
    </div>
    <div class="container2">
        <p class="element"> container2</p>
    </div>
    <div class="container3">
        <p class="element"> container3</p>
    </div>
    <div class="container4">
        <p class="element"> container4</p>
    </div>
    <div class="container5">
        <p class="element"> container5</p>
    </div>

这个是效果图:

image.png

如果您有更好的方法,非常您的欢迎补充!(还不熟悉发布功能,排版可能不好,还请见谅!)