• css样式水平居中和垂直居中的方法


    水平居中(包含块中居中)

    1. 定宽,左右margin为auto。(常规流块盒、弹性项目[不用定宽])

    例子:在box1盒子上设置宽,再设置margin:auto;

    <style>
        .box1 {
            width: 200px;
            height: 200px;
            background-color: black;
            margin: auto;
        }
    </style>
    
    <body>
        <div class="box-all">
            <div class="box1"></div>
        </div>
    </body>

    得到的效果:

    2. 弹性盒设置justify-content: center,让弹性项目在主轴上居中。(普遍适应)

    例子:在其父元素上设置弹性盒子,和对齐方式;

    <style>
        .box-all {
            display: flex;
            justify-content: center;
        }
        
        .box1 {
            width: 200px;
            height: 200px;
            background-color: black;
        }
    </style>
    
    <body>
        <div class="box-all">
            <div class="box1"></div>
        </div>
    </body>

    得到的效果:

    3. 父元素设置text-align: center,让其内部的行盒、块盒居中(文本)。

    例子:在盒子上设置text-align:center;文本自动居中;

    <style>
        p {
            text-align: center;
        }
    </style>
    
    <body>
        <div class="box-all">
            <p>这是一段文本。</p>
        </div>
    </body>

    得到的效果:

     

    4. 相对定位元素,margin-left:50%; transform:translateX( -50%)。[margin,padding相对于包含块宽度的百分比] 【终极方案】

    例子:对盒子设置相对定位属性,在用上面方式进行定位;

    <style>
        .box1 {
            width: 200px;
            height: 200px;
            background-color: black;
            position: relative;
            margin-left: 50%;
            transform: translateX(-50%);
        }
    </style>
    
    <body>
        <div class="box-all">
            <div class="box1"></div>
        </div>
    </body>

    得到的效果:


    垂直居中(方法与上面类似,我就不演示了)

    1. 单行文本垂直居中,设置父元素的line-height为包含块高度。

    2. 弹性盒设置align-items:center,让弹性项目在侧轴上居中。

    3. 相对定位元素,top:50%;transform:translateY(-50%)。【终极方案】

  • 相关阅读:
    .NET2.0基础类库中的范型——FunctionalProgramming
    原则
    080711 30℃
    关于mcp
    080714 33℃
    080715 31℃
    080716 30℃
    11号
    iOS-调用系统的短信和发送邮件功能,实现短信分享邮件分享
    UIView总结
  • 原文地址:https://www.cnblogs.com/Taiweis/p/11568533.html
Copyright © 2020-2023  润新知